excel - 带有数组的 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'
解决方案
您遇到的问题是您在过滤数组时不能使用通配符(“/*”)。
绕过这个限制很困难,但并非不可能。我以前做过的方法是做这样的事情:
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
方法二:
两点:
- 您不需要 FOR 循环。Criteria1=tab 将过滤所有条件,不需要循环
- 如果您使用此数组方法搜索多个术语,则不能使用通配符。如果要使用通配符,则必须使用不同的语法并且仅限于两个术语
代码 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
同样,您不能使用自动过滤器来过滤两个以上的带有通配符的术语
推荐阅读
- javascript - 如何在反应js中将值从post.map更改为初始状态
- angularjs - 修剪尾随空格并在没有可见输入时显示占位符 - Angularjs
- azure - 在同一个程序集中有多个工作,但在日志/列表中分开
- azure-devops - Azure DevOps 中带有手动步骤的整个管道超时
- cassandra - Cassandra “compactionstats”和“garbagecollect”
- java - 应用程序卡在“配置 OrikaBean 映射器”。为什么?
- c++ - 初始化与类相同类型的静态成员(静态初始化顺序问题)
- react-navigation - 如何在 createMaterialTopTabNavigator react-navigation v4 上启用惰性?
- python - 将文本文件转换为特定格式的 json ( python )
- python - SyntaxError:无效语法(扫描并连接 wifi)