在If语句中使用Like "*"操作符。

问题描述 投票:0回答:1

我试图基于四个组合框创建一个过滤器,以过滤一个子表单中的记录。问题是,组合框中RowSource列表中的一个值在基础查询中不存在。All". 我打算在所有的组合框上使用相同的代码。AfterUpdate 事件。请看我下面的方法,必要时请给予建议。目前,我收到一个类型不匹配的错误,在 Me.Combobox1.Value = "Like "*""

If IsNull(Me.combo1.Value) Or IsNull(Me.combo2.Value) Or IsNull(Me.combo3.Value) Or 
IsNull(Me.combo4.Value) Then
Exit Sub
End If

If Not IsNull(Me.combo1.Value) Or Not IsNull(combo2.Value) Or Not IsNull(combo3.Value) Or Not 
IsNull(combo4.Value) Then

If Me.combo1 = "All" Then
Me.combo1.Value = "Like " * ""
ElseIf Me.combo2.Value = "All" Then
Me.combo2.Value = "Like " * ""
ElseIf Me.combo3.Value = "All" Then
Me.combo3.Value = "Like " * ""
ElseIf Me.combo4.Value = "All" Then
Me.combo4.Value = "Like " * ""

Task1 = "SELECT * FROM qryBase WHERE [Quarter] = '" & Me.combo1.Value & "' AND [CurrentArea] = '" & 
Me.combo2.Value & "' AND [CurrentStatus] = '" & Me.combo3.Value & "' AND [MainUser] = '" & 
Me.combo4.Value & "'"

End If

End If
sql ms-access access-vba
1个回答
1
投票

就像现在这样,你的查询不能正常工作。LIKE 是为了取代 = 在条件语句中。然而, LIKE 没有通配符的情况下,就像 =. 因此,把 LIKE 操作符在SQL语句中。

Dim cbo1, cbo2, cbo3, cbo4 As String
...
If Me.combo1 = "All" Then
    cbo1 = "*"
ElseIf Me.combo2.Value = "All" Then
    cbo2 = "*"
ElseIf Me.combo3.Value = "All" Then
    cbo3 = "*"
ElseIf Me.combo4.Value = "All" Then
    cbo4 = "*"
End If

Task1 = "SELECT * FROM qryBase WHERE [Quarter] LIKE '" & cbo1 & "'" _
         & " AND [CurrentArea] LIKE '" & cbo2 & "'" _
         & " AND [CurrentStatus] LIKE '" & cbo3 & "'" _
         & " AND [MainUser] LIKE '" & cbo4 & "'"

Me.frmDatasheet.Form.Recordsource = Task1
Me.frmDatasheet.Form.Requery

但是,由于组合框可以有省略号,所以可以考虑参数化,避免将VBA值直接连接到SQL中,而是将其作为参数绑定。

Dim qdef As QueryDef
Dim rst As Recordset
Dim sql AS String
Dim cbo1, cbo2, cbo3, cbo4 As String

sql = "PARAMETERS cbo1 TEXT, cbo2 TEXT, cbo3 TEXT, cbo4 TEXT;" _
        & "SELECT * FROM qryBase WHERE [Quarter] LIKE [cbo1]" _
        & " AND [CurrentArea] LIKE [cbo2]" _
        & " AND [CurrentStatus] LIKE [cbo3]" _
        & " AND [MainUser] LIKE [cbo4]"

If Me.combo1 = "All" Then
    cbo1 = "*"
ElseIf Me.combo2.Value = "All" Then
    cbo2 = "*"
ElseIf Me.combo3.Value = "All" Then
    cbo3 = "*"
ElseIf Me.combo4.Value = "All" Then
    cbo4 = "*"
End If

' INITIALIZE QUERY OBJECT
Set qdef = CurrentDb.CreateQueryDef("", sql)
' Set qdef = CurrentDb.QueryDefs("mySavedParamQuery")

' BIND PARAMS
qdef!cbo1 = cbo1
qdef!cbo2 = cbo2
qdef!cbo3 = cbo3
qdef!cbo4 = cbo4

' SET FORM RECORDSET TO EXECUTED QUERY 
Set rst = qdef.OpenRecordset()    
Set Me.frmDatasheet.Form.Recordset = rst

Set rst = Nothing: Set qdef = Nothing
© www.soinside.com 2019 - 2024. All rights reserved.