[英]VBA autofilter using an array - ignore criteria if it is not in the filtered list
[英]VBA AutoFilter multiple worksheets based on array of numbers, ignore if not in list
假设我有一本包含3个工作表的工作簿。 我根据等于俄亥俄州的 State过滤了第一张表。 然后,我从列ID的筛选列表中获取值列表,并将它们放入Integer / Long数组中。 基本上,我将状态列Ohio的每一行的所有ID都放入。
现在我想筛选基于其ID列在那里我的ID阵列匹配其余的表。 问题是,当遇到未包含在新工作表中的已过滤ID时 ,我没有为我提供每张工作表的匹配项,而是只剩下最后一个匹配值。 这是我的VBA尝试过滤剩余工作表的示例:
For Each sheet In Worksheets
If sheet.Name <> "Sheet1" Then
sheet.Activate
columnNum = ActiveSheet.UsedRange.Find("ID").Column
ActiveSheet.AutoFilterMode = False
ActiveSheet.UsedRange.AutoFilter
'***Problem is here
ActiveSheet.UsedRange.AutoFilter Field:=columnNum, Criteria1:=mainIDs, Operator:=xlFilterValues
End If
Next
正如我前面提到的, mainIDs
是一个整数数组,该整数被带到每个工作表上进行过滤。 为什么只带我回到最后一场比赛? 我是否需要以某种方式告诉它忽略新表中没有的过滤值? 怎么样?
编辑:这就是我填充数组的方式
Dim mainIDs() As Long, size As Integer, i As Integer
size = ActiveSheet.UsedRange.Columns(1).SpecialCells(xlCellTypeVisible).Cells.Count - 2
ReDim mainIDs(size)
i = 0
For Each row In .UsedRange.Columns(1).SpecialCells(xlCellTypeVisible)
If row.Value <> "ID" Then '***Column header
mainIDs(i) = row.Value
i = i + 1
End If
Next
如果使用数组进行过滤,则必须先将值转换为字符串。 据我了解,您正在向数组添加整数/长整数值。 自动筛选器无法与此配合使用。
另外,您必须将数组更改为字符串数组mainIDs() as String
或将其声明为Variant。
For Each row In .UsedRange.Columns(1).SpecialCells(xlCellTypeVisible)
If row.Value <> "ID" Then '***Column header
mainIDs(i) = Cstr(row.Value) 'Cast values to string
i = i + 1
End If
Next
然后它应该起作用,请告诉我它是否对您有帮助。
如果将数组用作Criteria ,则必须使用一维数组。
但是,然后,您需要提供Operator
参数来实际过滤数组中的所有内容。
样品:
ActiveSheet.UsedRange.AutoFilter Field:=columnNum, _
Criteria1:=mainIDs, _
Operator:xlFilterValues
要了解有关自动筛选方法的更多信息,请检查MSDN 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.