如何创建参数化访问查询并使用excel vba中的变量对其进行初始化

时间:2012-02-19 17:26:08

标签: excel ms-access excel-vba vba

您可以帮我了解如何创建动态访问查询(参数化访问查询)&

使用excel vba中的变量初始化它

eX:选择&来自id = 1的客户

其中id = 1应使用类似于id = @id

的变量进行初始化

1 个答案:

答案 0 :(得分:3)

这是我在Access中创建和测试的参数查询。

PARAMETERS [@id] Long;
SELECT c.id, c.customer_name
FROM customers AS c
WHERE (((c.id)=[@id]));

我可以在Excel中使用ADO为参数指定值,并根据该查询检索记录集。这是我在Excel中创建的新模块的代码。

Option Explicit

Public Sub AdoCommandWithParameter()
    Const cstrDbPath As String = "C:\share\Access\whiteboard2003.mdb"
    'Dim cmd As ADODB.Command '
    'Dim cn As ADODB.Connection '
    'Dim rs As ADODB.Recordset '
    Dim cmd As Object
    Dim cn As Object
    Dim rs As Object
    Dim strConnString As String
    Dim strSql As String

    strSql = "PARAMETERS [@id] Long;" & vbCrLf & _
        "SELECT c.id, c.customer_name" & vbCrLf & _
        "FROM customers AS c" & vbCrLf & _
        "WHERE (((c.id)=[@id]));"
    Debug.Print strSql

    strConnString = "Provider=Microsoft.ACE.OLEDB.12.0;" & vbCrLf & _
        "Data Source=" & cstrDbPath & ";" & vbCrLf & _
        "Mode=Share Deny None;"

    'Set cn = New ADODB.Connection '
    Set cn = CreateObject("ADODB.Connection")
    cn.CursorLocation = 3 ' adUseClient '
    cn.Open strConnString

    'Set cmd = New ADODB.Command '
    Set cmd = CreateObject("ADODB.Command")
    cmd.CommandText = strSql
    cmd.ActiveConnection = cn
    cmd.Parameters("[@id]") = 1
    Set rs = cmd.Execute

    Debug.Print "RecordCount: " & rs.RecordCount

    rs.Close
    Set rs = Nothing
    Set cmd = Nothing
    cn.Close
    Set cn = Nothing
End Sub

更改 cstrDbPath 的值以匹配Access数据库文件的位置和名称。

最棘手的部分是使连接字符串正确。如果您遇到问题,请参阅ConnectionStrings.com

我编写了该程序以使用ADO的后期绑定。如果您想要早期绑定,则需要为可用版本的 Microsoft ActiveX数据对象库设置引用。然后切换到我注释掉的行。

这是您设置参数值的行:

cmd.Parameters("[@id]") = 1

更改它以提供您想要的值;我们不知道这个价值来自哪里。

您可能希望对Debug.Print RecordCount以外的记录集执行某些操作,但我们不知道它可能是什么。 : - )