Private Sub Command2_Click()
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim varItem As Variant
Dim LArray() As String
Dim strCriteria As String
Dim strSQL As String
Dim TestArray() As String
Set db = CurrentDb()
Set qdf = db.QueryDefs("QBF_Query")
For Each varItem In Me!Command2.ItemsSelected
strCriteria = strCriteria & ",'" & Me!Command2.ItemData(varItem) & "'"
Next varItem
If Len(strCriteria) = 0 Then
MsgBox "You did not select anything from the list" _
, vbExclamation, "Nothing to find!"
Exit Sub
End If
strCriteria = Right(strCriteria, Len(strCriteria) - 1)
LArray = Split(strCriteria, ",")
Dim txt As String
Dim i As Long
For i = LBound(LArray) To UBound(LArray)
QueryAns (LArray(i))
Next i
End Sub
Sub QueryAns(valX As String)
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strSQL As String
Set db = CurrentDb()
Set qdf = db.QueryDefs("QBF_Query")
strSQL = "SELECT * FROM Contacts WHERE ActiveSource LIKE'*'&valX&'*'"
qdf.SQL = strSQL
DoCmd.OpenQuery "QBF_Query"
Set db = Nothing
Set qdf = Nothing
End Sub
在下面的程序中,我试图创建一个Multiselect ListBox,我用它来过滤查询(即如果某个工作表在MultiSelect中选择了值,则显示它)。为此,我将值作为String接收并在数组中解析它们。然后我将值传递给一个名为QueryAns的函数,该函数实际执行查询。当我运行它时,程序创建一个对话框并要求我设置ValX参数(即使我明确设置它)。我怎样才能防止这种情况发生?
答案 0 :(得分:2)
valX
是一个VBA变量;数据库引擎一无所知。因此,当它看到SELECT
语句的这一部分时... ActiveSource LIKE'*'&valX&'*'
...它假定valX
是您没有提供值的参数的名称。
在构建SELECT
时调整引号,使其包含该变量的值而不是变量名...
strSQL = "SELECT * FROM Contacts WHERE ActiveSource LIKE '*'" & valX & "'*'"