Excel VBA中的SQLfunction

对于那些不了解的人来说,向VBAmacros中添加SQLfunction是相当容易的。 以下文章提供了代码: http : //analystcave.com/excel-using-sql-in-vba-on-excel-data/

我修改了这一点(很高兴提供代码),以便它输出很好,并把它放在一个我可以调用的Sub。 这使我不必进行多种sorting,复制粘贴等,从大型工作表中查找特定的数据。

但是请注意,在使用来自Gmail等在线来源的工作簿时会出现问题:

.ConnectionString =“Data Source =”&ThisWorkbook.Path&“\”&ThisWorkbook.Name&“;”

这项工作很好,当文件被保存到一个驱动器,但从一个在线网站,Excel无法连接。 修改连接string的任何build议,当文件没有保存在任何地方?

对于任何有兴趣的人来说,这个代码(基于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开始的结果。