我对VBA还是很陌生,所以我正在寻找有关设置宏的帮助,该宏会将特定范围内的值添加到数组中,然后遍历该数组以更新数据透视表上的过滤器。但是,并非每个值都可以设置。这样的一个示例是,在100个值中仅设置了4个值,因此它只会循环遍历4次,并使用这4个值更新过滤器。我之前从未使用过for循环,因此对此的任何指导都将非常有帮助。
到目前为止,我的代码:
Sub Update_Filters()
Dim PortfolioCodes As Variant
PortfolioCodes = Sheets("Configuration Sheet").Range("C7:C45").Value
Sheets("List").PivotTables("List").PivotFields( _
"[Portfolio].[Portfolio Code].[Portfolio Code]").VisibleItemsList = Array( _
"[Portfolio].[Portfolio Code].&[ABC1]", "[Portfolio].[Portfolio Code].&[ABC2]", _
"[Portfolio].[Portfolio Code].&[XYZ1]", "[Portfolio].[Portfolio Code].&[XYZ2]")
End Sub
答案 0 :(得分:1)
在这里,您的问题有两个可能的答案:
Option Explicit
Sub Update_Filters()
'this code will filter one portfolio code at a time
Dim LastRow As Long
With ThisWorkbook.Sheets("Configuration Sheet")
LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
Dim PortfolioCodes As Variant
PortfolioCodes = .Range("C7:C" & LastRow).Value
End With
For i = LBound(PortfolioCodes) To UBound(PortfolioCodes)
ThisWorkbook.Sheets("List").PivotTables("List").PivotFields( _
"[Portfolio].[Portfolio Code].[Portfolio Code]").VisibleItemsList = _
Array("[Portfolio].[Portfolio Code].&[" & PortfolioCodes(i) & "]")
'some code
Next i
End Sub
Sub Update_FiltersALL()
'This code will filter all the portfolio codes in your range
With ThisWorkbook.Sheets("Configuration Sheet")
Dim LastRow As Long
LastRow = .Cells(.Rows.Count, "C").End(xlUp).Row
Dim i As Long
i = 1
ReDim PortfolioCodes(1 To LastRow - 6) As String
Dim C As Range
For Each C In .Range("C7:C" & LastRow)
If Not IsEmpty(C) Then
PortfolioCodes(i) = "[Portfolio].[Portfolio Code].&[" & C.Value & "]"
i = i + 1
End If
Next C
End With
ThisWorkbook.Sheets("List").PivotTables("List").PivotFields( _
"[Portfolio].[Portfolio Code].[Portfolio Code]").VisibleItemsList = PortfolioCodes
End Sub