首页 > 解决方案 > 在 Access 中使用文本框进行 VBA 搜索

问题描述

我对 Access 和 VBA 都很陌生。我创建了一个搜索按钮,根据在不同组合框中选择的内容来查找不同的项目。但是,我想添加另一个搜索条件,如果我在名为“txtNotes”的文本框中键入文本,我可以在“tbl_ContructionOrders”表中的名为“Notes”的表字段中查找看起来像匹配项的记录。匹配必须有点松散,因为每个人键入的注释都不同,并且希望使用此框来查找我们遇到类似问题的工作订单,并且可能有一种更简单的方法来找到上述问题的解决方案。

这是我到目前为止所拥有的,但它不起作用

Private Sub btnLookup_Click()
Dim strWhere As String


Me.Filter = True
strWhere = ""


    If IsNull(Me.txtNotes) Then
    
        If Not IsNull(Me.txtNotes) Then
        
            If strWhere <> "" Then
                strWhere = strWhere & " like [Notes] = """ & Me.txtNotes & """"
            
        Else
                strWhere = strWhere & "[Notes] = """ & Me.txtNotes & """"
             End If
         End If
         
         If Len(strWhere) <= 0 Then
        MsgBox "No Criteria", vbInformation, "No Input."
    Else
        Me.Filter = strWhere
        Me.FilterOn = True
        Me.Requery
    End If
    
    
    If Me.FilterOn Then
        If Me.Recordset.RecordCount = 0 Then
            MsgBox "Nothing Found."
        End If
        
    End If
    End Sub

标签: vbams-accessms-access-2010

解决方案


尝试这个:

Private Sub Command0_Click()

    'empty notes
    If IsNull(txtNotes.Value) Then
        MsgBox "No Criteria", vbInformation, "No Input."
        Exit Sub
    End If
    
    'search
    Filter = "[Notes] Like '*" & txtNotes.Value & "*'"
    FilterOn = True
    
    'count records
    If RecordsetClone.RecordCount = 0 Then
        MsgBox "Nothing Found."
        FilterOn = False
    End If
    
End Sub

如果您想在键入时搜索(过滤),请使用:

Private Sub txtNotes_Change()

    'search after x number of chars
    If Len(txtNotes.Text) <= 3 Then
        FilterOn = False
        Filter = vbNullString
    Else
        Filter = "[Notes] Like '*" & txtNotes.Text & "*'"
        FilterOn = True
    End If
    
End Sub

推荐阅读