如何在TextBoxes中使用“动态搜索”过滤两列或更多列

时间:2019-11-28 22:11:22

标签: excel vba

寻找答案,如何同时过滤两列。我有两个TextBoxes分别过滤A列和B列。仅当我输入其中之一时,它才起作用。是否可以从两个文本框中使用两个条件?

我正在寻找什么

enter image description here

    Private Sub TextBox1_Change()

If Len(TextBox1.Value) = 0 Then
    ActiveSheet.AutoFilterMode = False
Else
    If ActiveSheet.AutoFilterMode = True Then
        ActiveSheet.AutoFilterMode = False
    End If
ActiveSheet.Range("A3:A" & Rows.Count).AutoFilter field:=1, Criteria1:="*" & TextBox1.Value & "*"
End If

End Sub

Private Sub TextBox2_Change()
If Len(TextBox2.Value) = 0 Then
    ActiveSheet.AutoFilterMode = False
Else
    If ActiveSheet.AutoFilterMode = True Then
        ActiveSheet.AutoFilterMode = False
    End If
ActiveSheet.Range("B3:B" & Rows.Count).AutoFilter field:=1, Criteria1:="*" & TextBox2.Value & "*"
End If
End Sub

有帮助吗?我需要执行什么命令?

2 个答案:

答案 0 :(得分:0)

这是一个基本示例,说明如何使用工作表上的两个文本框进行过滤。

With ActiveSheet.Range("A1:B8")
    .AutoFilter field:=1, Criteria1:=TextBox1.Value
    .AutoFilter field:=2, Criteria1:=TextBox2.Value
End With

答案 1 :(得分:0)

我知道,此代码可能没有经过优化,但是可以像我想要的那样工作。

Private Sub TextBox1_Change()
If Len(TextBox1.Value) = 0 And Len(TextBox2.Value) = 0 Then
 ActiveSheet.AutoFilterMode = False
ElseIf Len(TextBox2.Value) = 0 Then
    If ActiveSheet.AutoFilterMode = True Then
    ActiveSheet.AutoFilterMode = False
End If
    ActiveSheet.Range("A3:A10").AutoFilter field:=1, Criteria1:=TextBox1.Value
Else
  If ActiveSheet.AutoFilterMode = True Then
    ActiveSheet.AutoFilterMode = False
End If

With ActiveSheet.Range("A3:B10")
    .AutoFilter field:=1, Criteria1:=TextBox1.Value
    .AutoFilter field:=2, Criteria1:=TextBox2.Value
End With
End If
End Sub

Private Sub TextBox2_Change()
If Len(TextBox1.Value) = 0 And Len(TextBox2.Value) = 0 Then
 ActiveSheet.AutoFilterMode = False
ElseIf Len(TextBox1.Value) = 0 Then
    If ActiveSheet.AutoFilterMode = True Then
    ActiveSheet.AutoFilterMode = False
End If
    ActiveSheet.Range("B3:B10").AutoFilter field:=1, Criteria1:=TextBox2.Value
Else
  If ActiveSheet.AutoFilterMode = True Then
    ActiveSheet.AutoFilterMode = False
End If

With ActiveSheet.Range("A3:B10")
    .AutoFilter field:=1, Criteria1:=TextBox1.Value
    .AutoFilter field:=2, Criteria1:=TextBox2.Value
End With
End If

结束子