vba - 从 Excel 运行 Access 查询

标签 vba excel ms-access-2007 ado

我正在尝试从 excel 访问中运行查询,然后使用 VBA 中的 ADO 将这些结果拉入 excel 文档。不幸的是,我无法弄清楚如何运行访问查询,以便将 Excel 工作表的事件单元格中的数据用作访问查询中的条件。

我正在运行 Excel 和 Access 2007。我在下面包含了到目前为止的代码。在此先感谢您的帮助。

Sub testdb()

Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Set con = New ADODB.Connection
With con
.Provider = "Microsoft.ACE.OLEDB.12.0"
.Open "H:\WBC\Lukas\STOP.accdb"
End With
con.Execute "HPRSearch"
   'the criteria field is 'Input', and I need to pull it from the active cell on the Excel Sheet
End Sub

最佳答案

您需要做的第一件事是在 Access 中设置参数化查询。比如说,Query1 是(其中 ID 是一个整数):

SELECT ID FROM Table1 WHERE ID = [MyID];

[MyID] 周围的括号如果不能解析为字段名称,将被视为参数。现在,假设我们要恢复 ID 为 1 的记录。在 Excel 中设置您的代码:
Sub testdb()

    Dim con As ADODB.Connection
    Dim cmd As ADODB.Command
    Dim prm As ADODB.Parameter
    Dim rs As ADODB.Recordset

    Set con = New ADODB.Connection
    Set cmd = New ADODB.Command

    With con
        .Provider = "Microsoft.ACE.OLEDB.12.0"
        .Open "H:\WBC\Lukas\STOP.accdb"
    End With

    With cmd
        .ActiveConnection = con
        .CommandText = "Query1"
        .CommandType = adCmdStoredProc

        .Parameters.Append cmd.CreateParameter("MyID", adInteger, adParamInput)
        .Parameters("MyID") = 1
    End With

    Set rs = New ADODB.Recordset
    rs.Open cmd

    Do Until rs.EOF
        Debug.Print rs.Fields("ID").Value
        rs.MoveNext
    Loop

    rs.Close
    con.Close

    Set cmd = Nothing
    Set rs = Nothing
    Set prm = Nothing
    Set con = Nothing

End Sub

此引用 adInteger 在此行中找到
.Parameters.Append cmd.CreateParameter("MyID", adInteger, adParamInput)

应替换为代表查询中参数的变量类型的正确常量(参见此处:http://www.w3schools.com/ado/met_comm_createparameter.asp)。在您的情况下,您将设置此行中表示的 Parameter 值
.Parameters("MyID") = 1

与您的单元格中的值。

就是这样。因此,您创建 Connection,创建 Command 对象(本质上是对 Access 查询的引用),设置 Command 对象的属性,包括参数,然后将结果带回记录集中。然后遍历记录集并使用这些值执行您想要的操作。

关于vba - 从 Excel 运行 Access 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24437642/

相关文章:

excel - 使用 VBA 循环遍历 Excel 中表格范围的第一列

vba - 计数器溢出错误

vba - 循环遍历每个工作簿中的工作簿和工作表vba

python - 无法按 Pandas 数据框中的时间戳编制索引

excel - 在粗体和斜体Excel VBA中连接不同的单元格

vba - Excel VBA : Refering to column indexes in Worksheet. 单元格()

vba - 错误 91 对象变量或未在范围内设置 block 变量

sql - Long Integer 可以存储字母吗?

ms-access - Microsoft Access 中的 Field 和 Field2 对象之间的主要区别是什么……?

perl - 将 perl 连接到 ms 访问