我想根据单元格A1:AG1中显示的值在表格上应用过滤器。但问题是当我的数据更新时,有时我在其他单元格中有值,如AH,AI等。这些值仅在第一行可用。
所以我试图为每个单元格添加一个循环,但它不起作用。如何更改我的代码以遍历单行中的每一列。帮帮我
String
答案 0 :(得分:1)
如下所示:
Dim ws As Worksheet
Dim ws2 As Worksheet
Dim arr2() As String
Dim i As Long
Set ws = Sheets("Main")
Set ws2 = Sheets("Sheet2")
Set Tbl = ws2.ListObjects("DataTable")
LastCol = ws2.Cells(1, ws2.Columns.Count).End(xlToLeft).Column
'above will give you the last column number in row one of sheet ws2
ReDim Preserve arr2(1 To LastCol) 're-size the array
'Set rng = Range("A1:A" & LastCol) 'set your range from column 1 to last
For i = 1 To LastCol 'loop through columns
arr2(i) = ws2.Cells(1, i).Value 'add value to array
'above number 1 represents Row 1, and i will loop through columns
Next i
Tbl.Range.AutoFilter Field:=12, Criteria1:=arr2, Operator:=xlFilterValues
'above will filter table column 12 with array values?
答案 1 :(得分:0)
我不知道我是否理解你的问题,只是替换:
Set rng = Range("A1:AG1")
使用:
Set rng = ws.range(ws.cells(1 , 1) , ws.cells(1 , ws.Cells.Columns.Count).End(xlToLeft).Column