我的最终目标是循环浏览一个ListBox
对象及其每个选定项目,我想要查询具有所选WHERE
条件的字段。具有两个字段A
和B
的表格的图像。注:在列表框的项目是一个distinct
查询领域A.VBA - 访问列表框选择的项目作为条件到自定义查询中的字段
的结果的图片显示会发生什么,当我从字段框A
选择2 and 3
。点击Query
后,它会将其追加到正下方的框中,并将其添加到正下方的框中。我的代码不会崩溃,不会出错,并且不会投诉,但它不起作用。 我记得ResultSet
作为表将从下面的代码片段返回。
Private Sub Command41_Click()
' Declare Variables
Dim frm As Form, ctl As Control
Dim varItm As Variant
Dim A_outputString As String
Dim B_outputString As String
Dim A_flag As Boolean
Dim B_flag As Boolean
' Set Variables
' Build A String
For Each varItm In Forms!Form1!A_LB.ItemsSelected
A_outputString = A_outputString & Forms!Form1!A_LB.ItemData(varItm) & ","
Next varItm
' Build B String
For Each varItm In Forms!Form1!B_LB.ItemsSelected
B_outputString = B_outputString & Forms!Form1!B_LB.ItemData(varItm) & ","
Next varItm
' Filter A String
If A_outputString <> "" Then
'MsgBox (outputString)
Forms!Form1!A_TB = A_outputString
A_flag = True
Else
'MsgBox ("No input selected")
A_flag = False
End If
' Filter B String
If B_outputString <> "" Then
'MsgBox (B_outputString)
Forms!Form1!B_TB = B_outputString
B_flag = True
Else
'MsgBox ("No input selected")
B_flag = False
End If
' Decision Making
If A_flag Then
'MsgBox ("A_FLAG ON")
End If
If B_flag Then
'MsgBox ("B_FLAG ON")
End If
' Testing Variables
Dim outputString As String
' Database Variables
Dim rs As DAO.Recordset
Dim db As DAO.Database
Dim strSQL As String
Set db = CurrentDb
'**** CORRECT SQL QUERY ****'
'
' SELECT T.A
' FROM Table1 T
' WHERE (((T.A)="1" OR (T.A)="2"));
'
' BUILD AND STATEMENTS
Dim andStatements As String
andStatements = "("
For Each varItm In Forms!Form1!A_LB.ItemsSelected
andStatements = andStatements & "(T.A)=" & Chr(34) & Forms!Form1!A_LB.ItemData(varItm) & Chr(34) & " OR "
Next varItm
andStatements = Left(andStatements, Len(andStatements) - 5)
andStatements = andStatements & ")"
strSQL = "SELECT T.A FROM Table1 T WHERE (" & andStatements & ");"
Forms!Form1!SQL_TB = strSQL
Set rs = db.OpenRecordset(strSQL)
'Set rs = db.OpenRecordset(strSQL)
'Do While Not rs.EOF
' MsgBox (rs!myField) 'myField is a field name in table myTable
' rs.MoveNext 'press Ctrl+G to see debuG window beneath
'Loop
End Sub
所以正确的语法生成,因为我没有在访问查询生成器的确切相同的查询,并且那它究竟是如何期待。
想法?
编辑1:
改变AND
SQL逻辑OR
SQL逻辑后,我得到以下错误:
好的来电!我解决了这个问题,但现在我实际上遇到了一个错误。我更新了这个问题。 – bmc
@bmc很高兴帮助。你知道如何提出有用的答案吗? – Horaciux