我想创建一个按钮,当用户按下该按钮时,它将执行以下操作:
我尝试了这个,但是在.PivotItems(a(g)).Visible = True
中,它给了我对象必需的错误
Public Function GetLength(a As Variant) As Integer
If IsEmpty(a) Then
GetLength = 0
Else
GetLength = UBound(a) - LBound(a) + 1
End If
GL = GetLength
End Function
Public Function a(ByVal rng As Range) As Variant
Dim f As Long, r As Range
ReDim arr(1 To rng.Count)
f = 1
For Each r In rng.Cells
arr(f) = r.Value
f = f + 1
Next r
a = arr
End Function
Sub Macro6()
Dim rngCopy As Range
Dim rngPaste As Range
Dim rng As Range
Set rng = Selection
Sheets("Pivot_All").Activate
ActiveSheet.PivotTables("PivotTable1").PivotFields("Empl").ClearAllFilters
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Empl")
For i = 1 To .PivotItems.Count - 1
.PivotItems(.PivotItems(i).Name).Visible = False
Next i
End With
With ActiveSheet.PivotTables("PivotTable1").PivotFields("Empl")
For g = 0 To GL
.PivotItems(a(g)).Visible = True
Next g
End With
End Sub
答案 0 :(得分:0)
a
正在等待范围a(ByVal rng As Range)
,但是您提交了一个数字g
作为参数。您必须改为提交Range
对象。
在您的过程中也未定义GL
,我假设您想使用GetLength
。
所以应该是这样的:
Dim ResultOfA As Variant
ResultOfA = a(Range("your range here"))
For g = 0 To GetLength(ResultOfA)
.PivotItems(ResultOfA(g)).Visible = True
Next g
我建议始终激活Option Explicit
:在VBA编辑器中,转到工具› 选项› Require Variable Declaration
请注意,您可以在一行中将连续范围读入数组:
Dim ArrValues() As Variant
ArrValues = Range("A1:A10").Value
Debug.Print ArrValues(1, 5) '= A5
如果使用此功能,则可能不再需要功能a
。
您最终会得到类似的东西:
Option Explicit
Public Sub Macro6()
Dim rngCopy As Range
Dim rngPaste As Range
Dim rng As Range
Set rng = Selection
Dim ws As Worksheet
Set ws = Worksheets("Pivot_All")
With ws.PivotTables("PivotTable1").PivotFields("Empl")
.ClearAllFilters
Dim i As Long
For i = 1 To .PivotItems.Count - 1
.PivotItems(.PivotItems(i).Name).Visible = False
Next i
Dim ResultOfA As Variant
ResultOfA = a(rng)
If Not IsEmpty(ResultOfA) Then
Dim g As Long
For g = LBound(ResultOfA) To UBound(ResultOfA)
.PivotItems(ResultOfA(g)).Visible = True
Next g
End If
End With
End Sub
Public Function a(ByVal rng As Range) As Variant
Dim f As Long, r As Range
ReDim arr(1 To rng.Count)
f = 1
For Each r In rng.Cells
arr(f) = r.Value
f = f + 1
Next r
a = arr
End Function