VBA ADODB- 使用同一工作簿的Excel表格作为数据库进行选择查询

3

我是VBA的初学者,如果问题水平较低,请不要介意。我正在尝试运行一个SQL查询,在其中从同一工作簿的一个工作表中提取数据。

在此输入图片描述

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代表阿姆尔公司,5代表雀巢公司等等。
关系表如下:

enter image description here

我不确定如何做到这一点。这些数字按顺序对应它们各自的产品公司。

将查询结果存储到数组中,循环遍历该数组,然后根据数组中的数据运行JOIN语句。 - Doug Coats
嗨,Doug Coats :) 我的查询没有结果。我不知道我的代码有什么问题。你能检查一下我的代码并告诉我哪里出了问题吗?接下来是将结果集存储在数组中并循环逻辑,请你帮我写一下代码好吗?我对此不是很清楚。我理解这个逻辑,但在 VBA 中实现时,切换工作表让我感到困惑。 - Naina
该表格的名称是Data还是sData? - Doug Coats
我认为那就是你的问题 :) - Doug Coats
当我输入Data时,它显示变量未定义。它将Data视为变量。 - Naina
显示剩余5条评论
1个回答

4

请看下面的示例,展示如何创建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;"";"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接