【问题标题】:Access VBA run query with values passed from a list box使用从列表框中传递的值访问 VBA 运行查询
【发布时间】:2020-10-02 18:31:51
【问题描述】:

我已在 Access 中制作了此表单,我希望完成以下任务。

这里的列表框包含两列,可以多选。我想使用第二列(右列)的值并将它们传递到我为下面的“test2”按钮设置的查询中。

这是我的按钮点击事件的 VBA 代码。

Private Sub test2_Click()
Dim db As dao.Database
Dim qdef As dao.QueryDef
Dim strSQL As String
Set db = CurrentDb


'Build the IN string by looping through the listbox
For i = 0 To Select_Counties2.ListCount - 1
    If Select_Counties2.Selected(i) Then
        strIN = strIN & "'" & Select_Counties2.Column(1, i) & "',"
    End If
Next i

'Create the WHERE string, and strip off the last comma of the IN string
strWhere = " WHERE County_GEOID in " & "(" & Left(strIN, Len(strIN) - 1) & ")"

strSQL = strSQL & strWhere

    
Set qdef = db.CreateQueryDef("User query results", strSQL)
qdef.Close
Set qdef = Nothing
Set db = Nothing
DoCmd.OpenQuery "User query results", acViewNormal
End Sub

我收到此错误:

谁能告诉我我在代码中做错了什么?谢谢!

【问题讨论】:

  • 你只有 WHERE 而没有查询类型或数据源
  • strSQL 的值是多少?我看不到你在哪里设置的。我只看到Where 子句。
  • 一点点调试工作应该会发现逻辑缺陷。逐步调试您的代码。使用 Debug.Print 语句查看变量的值,尤其是使用代码构建的长 SQL 语句。使用 Watches 窗口。
  • 是的,您可以添加Debug.print ("my SQL request : " & strSQL)
  • 我的错。我错过了选择语句。我刚刚添加了它。strSQL = "SELECT * FROM age 但查询没有返回任何内容

标签: sql vba ms-access


【解决方案1】:

在微软的这个例子中,他们没有解释就调用了 application.refreshwindow。 https://docs.microsoft.com/en-us/office/client-developer/access/desktop-database-reference/database-createquerydef-method-dao

我认为您的代码失败了,因为访问无法找到刚刚添加到其查询集合中的查询。此外,您生成的 sql 不再有效。 所以:用你自己的有效sql替换我的sql

Private Sub test2_Click()
Dim db As DAO.Database
Dim qdef As DAO.QueryDef
Dim strSQL As String
strSQL = "PARAMETERS GEOID Number; " 'without valid sql this code doesn't run so 
                                    'replace my sql with your own.
strSQL = strSQL & "SELECT GEOID FROM Counties"
Set db = CurrentDb

For i = 0 To Select_Counties2.ListCount - 1
    If Select_Counties2.Selected(i) Then
        strIN = strIN & Select_Counties2.Column(1, i) & ","
    End If
Next i

strWhere = " WHERE County_GEOID in " & "(" & Left(strIN, Len(strIN) - 1) & ")"
strSQL = strSQL & strWhere
Debug.Print strSQL
'now the important bit:
db.CreateQueryDef ("User query results") 'create the query
Application.RefreshDatabaseWindow 'refresh database window so access knows it has a new query.
'query will now be visible in database window.  make sure to delete the query between runs
 'Access will throw an error otherwise
Set qdef = db.QueryDefs("User query results")
qdef.SQL = strSQL
qdef.Close
Set qdef = Nothing
Set db = Nothing
DoCmd.OpenQuery "User query results", acViewNormal
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多