简体   繁体   English

使用 OR 运算符从多列文本框中的值动态过滤表

[英]Dynamic filtering of a table with value from a textbox in multiple column with OR operator

I am trying to develop a search functionality in a worksheet, related to a dynamic filtering via VBA我正在尝试在工作表中开发搜索功能,与通过 VBA 进行的动态过滤相关

EXPECTED RESULT: When I start typing in a textbox, a table is filtered if what I write is in column 1 OR in column 2.预期结果:当我开始在文本框中键入内容时,如果我在第 1 列或第 2 列中写入内容,则会过滤表格。


In the worksheet I have a table (G10:J78) called "tbl_Data"在工作表中,我有一个名为“tbl_Data”的表 (G10:J78)

I insert a Textbox (name is TextBox1) on cell D8 and linked it to D8 so that what I write in the textbox is written in D8.我在单元格 D8 上插入一个文本框(名称为 TextBox1)并将其链接到 D8,这样我在文本框中写的内容就会写在 D8 中。 Then, in the TextBox1 code, I wrote:然后,在 TextBox1 代码中,我写道:

Private Sub TblBox_Change()
Application.ScreenUpdating = False

With ActiveSheet.ListObjects("tbl_Data")
.Range.AutoFilter field:=1, Criteria1:=("*" & (d8) & "*"), Operator:=xlOr 
.Range.Autofilter field:=2, Criteria1:=("*" & (d8) & "*"), Operator:=xlFilterValues 
End With
Application.ScreenUpdating = True
End Sub

This is solution does not work, as it only works with first column (field:=1).这是解决方案不起作用,因为它只适用于第一列(字段:=1)。

Anyone has a solution for this?有人对此有解决方案吗?

give this a try.试一试。

Private Sub TblBox_Change()

Application.ScreenUpdating = False

Dim trgtRng As Range
Dim table As ListObject

Set table = ActiveSheet.ListObjects("tbl_Data")
Set ws = ActiveSheet

With table
    .Range.AutoFilter field:=1, Criteria1:=("*" & (d8) & "*"), Operator:=xlOr
    Set trgtRng = .DataBodyRange
    If trgtRng Is Nothing Then
        'if there are no results then you need to clear the filter first
        If (ws.AutoFilterMode And ws.FilterMode) Or ws.FilterMode Then
          ws.ShowAllData
        End If
        ' and then you need to apply the filter on the second column
        .Range.AutoFilter field:=2, Criteria1:=("*" & (d8) & "*"), Operator:=xlFilterValues
    End If
End With

set ws = nothing
set table = nothing
Application.ScreenUpdating = True

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM