[英]Excel VBA Autofilter using array - multiple values in same column
I feel like the answer is out there, but after lots of searching and experimenting, I am still coming up short. 我觉得答案就在那里,但是经过大量的搜索和尝试,我仍然很短。
So can see in the first image that column O had a comma separated list of values. 因此可以在第一张图片中看到,列O具有逗号分隔的值列表。 I would like my routine to filter the data on column A using the entire list when the user double click on the cell containing the list. 当用户双击包含该列表的单元格时,我希望我的例程使用整个列表来过滤A列上的数据。
My code reads: 我的代码是:
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$8").AutoFilter Field:=1, Criteria1:=newIDArray
End If
Cancel = False
End Sub
However the result is the following image. 但是结果是下面的图像。 I looks like it is taking the filter in column A, deselecting All and showing results .... it is not using the values from the comma delimited list at all. 我似乎正在采用A列中的过滤器,取消选择全部并显示结果..它根本没有使用逗号分隔列表中的值。
Any thoughts on what is happening? 有什么想法吗? Thanks for reading. 谢谢阅读。
On my setup: 在我的设置中:
Range("J1:J3")
逗号分隔的值对应于Range("J1:J3")
Range("A1:A18")
要过滤的范围对应于Range("A1:A18")
Please see correct way to appropriately size ( ReDim
) an array and how to add values to it below 请在下面查看正确调整数组大小( 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.