访问如何使用Me.Filter cmd

时间:2017-11-06 02:26:39

标签: ms-access filter

我有一个处理过滤功能的问题。

当我输入关键字时,使用按钮搜索是否有任何相关数据时我没问题。我的代码就像,

.my-container{
    margin:auto;
    width:200px;    
}

但是,一旦我想搜索多个关键字,它就无法运作。 我的代码如下,

Private Sub Command112_Click()
    Dim strSearch As String
    Dim strFilter As String

    strSearch = "'*" & Forms![TestForm].SearchInput & "*'"
    Debug.Print strSearch

    strFilter = _
    "[IMSDP] Like " & strSearch & _
                " Or [EN8] Like " & strSearch & _
                " Or [EN10] Like " & strSearch & _
                " Or [Card] Like " & strSearch & _
                " Or [Status] Like " & strSearch & _
                " Or [IMSDP] Like " & strSearch

    Debug.Print strFilter

    Me.Filter = strFilter
    Me.FilterOn = True
End Sub

有人可以帮忙吗?谢谢。

我现在的代码如下,(您可能认为Status = IMSDP)

Private Sub Search_Click()

    Dim strSearch As Variant
    Dim strFilter1 As Variant
    Dim strFilter2 As Variant
    Dim SpacePosition As Variant
    Dim Lstr As Variant
    Dim Rstr As Variant
    Dim IMSDP1 As Variant
    Dim IMSDP2 As Variant

    strSearch = "'*" & Forms![tryForm].IMSDPInput & "*'"
    Debug.Print strSearch

    SpacePosition = InStr(1, [strSearch], " ")
    Lstr = Trim(Left([strSearch], [SpacePosition] - 1))
    Rstr = Trim(Right([strSearch], Len([strSearch]) - [SpacePosition]))

    IMSDP1 = Lstr
    IMSDP2 = Rstr

    MsgBox "IMSDP1 is " & IMSDP1 & " and IMSDP2 is " & IMSDP2 & ""

    strFilter1 = _
    "[IMSDP] Like " & IMSDP1 & _
    "And [IMSDP] Like " & IMSDP2

    Me.Filter = strFilter
    Me.FilterOn = True

End Sub

如果我只输入一个关键字(例如" 20")进行搜索,但如果我输入类似" 20 27"

的内容,则会失败。

我只知道我可以在Excel中编写,例如,Range(" A1")。AutoFilter字段:= 5,Criteria1:= Status1,Operator:= xlOr,Criteria2:= Status2但我不知道如何在Access

中执行此操作

1 个答案:

答案 0 :(得分:1)

如果“状态”字段是数字类型,并且用户始终输入以空格分隔的“关键字”,请考虑以下事项:

Private Sub Command14_Click()
If Not IsNull(Me.StatusInput) Then
   Me.Filter = "IN(" & Replace(Me.StatusInput, " ", ",") & ")"
End If
Me.FilterOn = True
End Sub

如果他们用逗号分隔,更简单: Me.Filter = "IN(" Me.StatusInput & ")"

对于文本字段:
"IN('" & Replace(Me.StatusInput, " ", "','") & "')"

"IN('" & Replace(Me.StatusInput, ",", "','") & "')"

无论代码结构如何,都取决于用户是否正确且一致地在文本框中输入字符串。

如果您想要更多地控制用户可以输入的值,请使用多选列表框,并通过列表框中的VBA循环选择项来构造逗号分隔值条件。一个相当常见的主题和许多可用于循环列表框的代码示例。

毕竟不需要阵列!