如何用SQL语法处理Excel数据? ADO对象在Excel中的处理
-
ActiveX Data Objects (ADO) 让我们能够用一个工具来操作SQL Server, Access DB, Worksheet
ADO有很多用法,首先介绍一个:把excel中的表用SQL语法来处理
使用ADO流程是
- 建立连接
- 写SQL语句
- 执行SQL语句
要使用ADO,首先要打开编辑VBA的界面,上面的菜单栏里面有一个是Tools,点击Tools, 里面找到reference。勾选上Microsoft ActiveX Data Objects 6.1 Library(如果没有6.1版本,也可以用2.8版本)
建立连接的基本语法如下
Dim Con as new ADODB.Connection Con.Open "Connection string" '运行SQL语句 Con.Close
这里的connection string需要根据不同的Excel版本确定
https://www.connectionstrings.com/ 这个网站提供了不同情况下需要用到的connection string
我的excel版本是2016,我用的connection string如下
strFileName=ThisWorkbook.Fullname "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & strFileName & "; Extended Properties=""Excel 12.0 Macro;HDR=Yes"";"
就可以成功连接到目前用的工作表啦
-
第二步是运行SQL。首先讲讲SELECT要怎么用
- 创建新对象:Recordset,用于储存SELECT运行出来的结果
Dim rs As New ADODB.Recordset '如果你想要运行SQL的表是一个命了名的区域 strSQL="SELECT * FROM range" ’如果要运行的表是一整个worksheet ‘如果数据超过65536行,由于一个excel bug,只能用下面这种方法引用表 strSQL="SELECT * FROM [Sheet1$\$$]" '如果是一个未命名区域 strSQL="SELECT * FROM [Sheet1$\$$A1:O60]" 'con是刚刚用到的ADO connection rs.Open strSQL, con rs.Close
- 把运行出来的结果保存到一个新建的excel表
Dim ws As Worksheet Set ws = output 'Application.Sheets.Add ws.Cells.ClearContents 'Write the header Dim i As Long For i = 0 To rs.Fields.Count - 1 ws.Cells(1, i + 1).Value2 = rs.Fields(i).Name Next i ws.Range("A2").CopyFromRecordset rs
完整代码如下
Sub ADOBD_SELECT() Dim strFileName As String Dim ConnectionString As String 'Fullname means the folder path is included strFileName = ThisWorkbook.FullName 'From website https://www.connectionstrings.com/ 'HDR=Yes -> my data set has heading ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & strFileName & "; Extended Properties=""Excel 12.0 Macro;HDR=Yes;"";" Dim conn As New ADODB.Connection 'Recordset: where the result of the query will be placed Dim rs As New ADODB.Recordset Dim strSQL As String 'Write the query strSQL = Range("Query") conn.Open ConnectionString rs.Open strSQL, conn Dim ws As Worksheet Set ws = output 'Application.Sheets.Add ws.Cells.ClearContents 'Write the header Dim i As Long For i = 0 To rs.Fields.Count - 1 ws.Cells(1, i + 1).Value= rs.Fields(i).Name Next i ws.Range("A2").CopyFromRecordset rs rs.Close conn.Close Set conn = Nothing Set rs = Nothing End Sub