首页 > 解决方案 > 带有数组的 AutoFilter

问题描述

我试图通过查看单元格是否包含这些名称之一来过滤我的表格,当我使用 theFor 时,它会在一行中显示所有数据。

这是代码:

    Dim tab(3) as string '
    'tab(0) = "*valerie dupond*"'
'tab(1) = "*emanuel babri*"'
'tab(2) = "*raphael gerand*"'

For i = 0 To 2

'Worksheets("Feuil1").Range("A1").AutoFilter field:=2, Criteria1:=tab , ''Operator:=xlFilterValues'

'Next'

标签: excelvba

解决方案


您遇到的问题是您在过滤数组时不能使用通配符(“/*”)。

​​​

绕过这个限制很困难,但并非不可能。我以前做过的方法是做这样的事情:

1)将您要过滤的列(我认为是第 2 列)中的所有值复制到空白表中。

2) 删除重复项。

3) 遍历所有剩余的行并删除任何不符合条件的行。

4) 将剩余的值放入一个数组中。

5)过滤该数组上的原始数据。

我无权访问代码,但它类似于下面的内容。我没有测试它。我现在不在使用 Excel 的计算机上,因此您必须清理它、修复错误并在 Visual Basic 中启用正则表达式。应该在工具->参考菜单中。你也可以稍微修改一下这段代码来操作它。

Dim i As Integer

Dim c As Integer

Dim lRow As Integer

Dim regEx As New RegExp

Dim rEx As String

Dim arr(1) As String



lRow = Range(shSheet.Rows.Count, ActiveCell.Column).End(xlup).Row 'Get's the last row of the current column selected so make sure to select the column you are trying to filter.



rEx = "^.*(valerie dupond|emanuel babri|raphael gerand).*$" ' The test string for the Regular Expression to match


'Setting up the Regular Expression.

With regEx

.Global = True

.MultiLine = True

.IgnoreCase = False

.Pattern = strPattern

End With



i = 0 'Sets i to be looped through your values.

c = 1 'C will be set to store the values in the array.



'Loops through every row in your table trying to match the pattern above

For i to lRow

If regEx.Test(LCase(ActiveCell.Value)) Then
arr(c) = ActiveCell.Value

c = c + 1

ReDim Preserve arr(c)

End If

ActiveCell.Offset(1,0).Select
Next i



'Sets the filter

Worksheets("Feuil1").Range("A1").AutoFilter field:=2, Criteria1:=arr , ''Operator:=xlFilterValues

方法二:

两点:

  1. 您不需要 FOR 循环。Criteria1=tab 将过滤所有条件,不需要循环
  2. 如果您使用此数组方法搜索多个术语,则不能使用通配符。如果要使用通配符,则必须使用不同的语法并且仅限于两个术语

代码 2

只需删除通配符。例如,如果您只需要匹配“valerie dupond”而不是“Mrs. valerie dupond”

Sub FilterMe()
        Dim names(3) As String
        names(0) = "valerie dupond"
        names(1) = "emanuel babri"
        names(2) = "raphael gerand"
        Worksheets("Feuil1").Range("A1").AutoFilter field:=2, Criteria1:=names, Operator:=xlFilterValues
    End Sub

同样,您不能使用自动过滤器来过滤两个以上的带有通配符的术语


推荐阅读