Excel VBA 使用数组自动筛选 - 同一列中有多个值

Excel VBA Autofilter using array - multiple values in same column

我觉得答案就在那里,但经过大量的搜索和试验,我仍然没有找到答案。

所以可以在第一张图片中看到 O 列有一个逗号分隔的值列表。当用户双击包含列表的单元格时,我希望我的例程使用整个列表过滤 A 列上的数据。

我的代码是:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

If Not Intersect(Target, Range("O:O")) Is Nothing Then
    Sheet1.Cells.AutoFilter 'clear existing filters
    Dim idArray() As String
    idArray = Split(Target.Value, ",") 'store cell contents in array
    Dim newIDArray(0 To 100) As String
    Dim i As Long
    For i = 0 To UBound(idArray)
     newIDArray(i) = """" & CStr(idArray(i)) & """"   'wrap elements with quotes ... not sure if needed
    Next
    Sheet1.Range("$A").AutoFilter Field:=1, Criteria1:=newIDArray
End If

Cancel = False
End Sub

然而结果是下图。我看起来它正在使用 A 列中的过滤器,取消选择所有并显示结果....它根本没有使用逗号分隔列表中的值。

对正在发生的事情有什么想法吗?感谢阅读。

在我的设置中:

  • 逗号分隔值对应于Range("J1:J3")
  • 过滤范围对应Range("A1:A18")

请在下方查看适当调整 (ReDim) 数组大小的正确方法以及如何向其添加值


Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

Dim Arr          'Array to SPLIT string
Dim i As Long    'Index to loop through Arr
Dim Filt         'Array to filter range

If Not Intersect(Target, Range("J1:J3")) Is Nothing Then
    Arr = Split(Target, ",")
    ReDim Filt(LBound(Arr) To UBound(Arr))
        For i = LBound(Arr) To UBound(Arr)
            Filt(i) = CStr(Arr(i))
        Next i
    Range("A1:A18").AutoFilter 1, Filt, xlFilterValues
End If

End Sub