如何在导入excel文件时在vba中编写sql查询来过滤数据?

时间:2016-01-08 11:20:35

标签: sql excel-vba vba excel

我有一个excel文件(原始数据),我必须导入到另一个excel文件(可视化界面)。但是,在导入原始数据文件之前,我必须过滤掉某些列的数据。我可以在导入文件vba代码中编写SQL查询吗? 例如,我想过滤掉一列中的空白值,只查看另一列中大于10的数字。

1 个答案:

答案 0 :(得分:0)

这是可能的。在可视化界面文件(viz.xls)中,创建一个新模块并添加

  

Microsoft ActiveX数据对象2.8库

使用工具>>参考

以下代码将引导您进入球场:

Sub getFromRawData()
    Dim rawFile As String

    Dim adoConn As ADODB.Connection
    Dim adoRS As ADODB.Recordset
    Dim strSQL As String

    'The xlsx file to treat as a database
    rawFile = "c:\myFolder\myrawdatafile.xlsx"

    'Open a connection to the workbook
    adoConn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & rawFile & ";Extended Properties=""Excel 12.0 Xml;HDR=YES"";"

    'Write the SQL necessary to get the data you want (assuming Sheet1 and making up column names, which will be the first row of the sheet by default)
    strSQL = "SELECT * FROM [Sheet1$] WHERE [onecolumn] IS NOT NULL AND [anotherColumn] > 10;"

    'Now we open up our recordset using the connection and the sql statement
    adoRS.Open strSQL, adoConn

    'Last, we dump the results in this viz sheet
    ThisWorkbook.Sheet1.Range("A2").CopyFromRecordset adoRS

    'If you want the header row, you'll have to get that from the recordset:
    Dim adoField As ADODB.Field
    Dim intHdrCol

    'initial column to start writing header
    intHdrCol = 1

    'loop through the fields in the recordset and write the column
    For Each adoField In adoRS.Fields
        Sheet1.Cells(1, intHdrCol).Value = adoField.Name
        intHdrCol = intHdrCol + 1
    Next adoField


    'Close the connection
    adoRS.Close
    adoConn.Close

End Sub

根据您的Excel版本,您必须使用该连接字符串。显然,SQL语句也必须进行修改..但是通过一些修补,这个东西已经准备好摇滚了。