VBA ADODB-使用与数据库相同的工作簿的Excel工作表选择查询

时间:2016-11-26 11:33:01

标签: excel vba excel-vba ado

我是VBA的新手所以请不要介意问题是否是低级别的。我正在尝试运行SQL查询,其中必须从同一工作簿的一个工作表中提取数据。< / p>

enter image description here

SQL = "Select ProductNumber from [sData$] where ProductSource = " & pSource & "

'pSource is a string that stores Product Source
'sdata is a sheet named as Data in the workbook

dataPath = ThisWorkbook.Fullname

'Not sure if this is the value I shall send as datapath in getData function

Set rst = getData(dataPath,SQL)
rst.Open

getData函数定义如下

Public funtion getData(path as String, SQL as string) as ADODB.Recordset
Dim rs as ADODB.Recordset
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
cn.Open ("Provider= Microsoft.Jet.OLEDB.4.0;" & _
           "DataSource= " & path & ";"&_
            "Extended Properties=""Excel 8.0;HDR=Yes;FMT=Delimited;IMEX=1;""")
rs.ActiveConnection =cn
rs.Source= SQL
Set getData =rs
End Function

现在我从数据表中得到数字后,我需要找到相应的数据 产品公司来自关系表。 9代表Amul,5代表雀巢等。

关联:

enter image description here

我不知道该怎么做。这些数字按顺序对应各自的产品公司。

1 个答案:

答案 0 :(得分:1)

看一下下面的示例,演示如何创建与此工作簿的ADODB连接,从SQL查询获取ADODB记录集,从关系表中检索键 - 值对,创建和填充字典,以及从记录集输出值和字典中的相应值:

Option Explicit

Sub Test()

    Dim oCn As Object
    Dim oRs As Object
    Dim aKeys
    Dim aItems
    Dim i As Long
    Dim oDict As Object
    Dim dProdNum

    ' create ADODB connection to this workbook
    Set oCn = CreateObject("ADODB.Connection")
    oCn.Open _
        "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "DataSource='" & ThisWorkbook.FullName & "';" & _
        "Extended Properties=""Excel 8.0;HDR=Yes;FMT=Delimited;IMEX=1;"";"
    ' get ADODB recordset from SQL query
    Set oRs = oCn.Execute("SELECT DISTINCT ProductNumber FROM [Data$] WHERE ProductSource = 'A1'")

    ' retrieve key - value pairs from relation sheet
    With ThisWorkbook.Sheets("Relation")
        aKeys = Split(.Range("B1"), ",")
        aItems = Split(.Range("B2"), ",")
    End With
    ' create and populate a dictionary
    Set oDict = CreateObject("Scripting.Dictionary")
    For i = 0 To UBound(aKeys)
        oDict(Trim(aKeys(i)) + 0) = Trim(aItems(i))
    Next

    ' output the values from the recordset and the corresponding values from the dictionary
    oRs.MoveFirst
    Do Until oRs.EOF
        dProdNum = oRs.Fields(0).Value
        Debug.Print dProdNum & " - " & oDict(dProdNum)
        oRs.MoveNext
    Loop

End Sub

我的输出如下:

  

4 - Britanica
5 - Nestle
9 - Amul

注意,上面代码中的连接字符串显示为.xls文件。如果.xlsm你应该使用:

    oCn.Open _
        "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source='" & ThisWorkbook.FullName & "';" & _
        "Extended Properties=""Excel 12.0 Macro;HDR=Yes;FMT=Delimited;IMEX=1;"";"