ListBox
オブジェクトをループすることです。選択したアイテムごとにWHERE
条件を選択してフィールドをクエリします。 2つのフィールドがA
とB
のテーブルのイメージ。注意:リストボックス内の項目は、画像は、私がフィールドボックスA
から2 and 3
を選択したときにどうなるかを示しVBA - 選択したアイテムをカスタムクエリのフィールドに条件としてリストボックスに追加
フィールドAのdistinct
クエリの結果です。 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
私はそれが見えます正確にどのようにアクセスクエリビルダとのthatsにまったく同じクエリをしたので、それで正しい構文は、生成されます。
思考?
EDIT 1:
OR
SQLロジックにAND
SQLロジックを変更した後、私は次のエラーを取得する:
よろしくお願いします。私はそれを修正しましたが、実際にはエラーが発生しました。質問を更新しました。 – bmc
@bmc喜んで助けました。あなたは役に立つ答えをupvoteする方法を知っていますか? – Horaciux