对于那些不知道的人,将SQL功能添加到VBA宏相当容易。以下文章提供了代码:http://analystcave.com/excel-using-sql-in-vba-on-excel-data/
我对此进行了一些修改(很高兴提供代码),以便输出得很好并将其放入我可以调用的Sub中。这使我不必进行多种排序,复制粘贴等,以便从大型工作表中查找特定数据。
但是,请注意从在线来源处理工作簿时遇到的问题,例如Gmail的:
.ConnectionString =“Data Source =”& ThisWorkbook.Path& “\”& ThisWorkbook.Name& “;”
当文件保存到驱动器时,此工作正常,但从在线站点,Excel无法连接。有关在文件未保存到任何地方时修改连接字符串的任何建议吗?
答案 0 :(得分:1)
对于任何有兴趣的人来说,这段代码(基于Analyst Cave的代码)非常适合在VBA中使用SQL。将以下内容保存为Sub:
Option Explicit
Sub QuerySQL(result_location As Range, query As String)
Dim ResultWS As Worksheet
Set ResultWS = ThisWorkbook.Sheets("Query Results")
ResultWS.Cells.ClearContents
If query = "" Then Exit Sub
Dim cn As Object, rs As Object
'Add to the workbook a database connection with itself
'Note other ConnectionString could be used to access a variety of media
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & ThisWorkbook.Path & "\" & ThisWorkbook.Name & ";" & _
"Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
.Open
End With
'Build and execute the SQL query
Set rs = cn.Execute(query)
If rs.EOF = True Then Exit Sub
'Print column labels
Dim i As Long, j As Long
For i = 0 To rs.Fields.Count - 1
result_location.Offset(0, i).Value = rs.Fields(i).Name
Next i
'Print column contents
i = 0
Do
For j = 0 To rs.Fields.Count - 1
result_location.Offset(i + 1, j).Value = rs.Fields(j).Value
Next j
rs.MoveNext
i = i + 1
Loop Until rs.EOF
'Close the connections
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
要使用它,只需执行以下操作:
Dim myQuery As String
myQuery = "SELECT * FROM [Sheet2$]"
Call QuerySQL(ThisWorkbook.Sheets("Sheet1").Range("A1"), myQuery)
它使用MS Access样式SQL。上面将把Sheet2看作表格,并打印从Sheet1上的A1开始的结果。