如何在with语句中修复对象在vba中的错误?

时间:2019-05-02 07:58:14

标签: excel vba pivot-table

我想创建一个按钮,当用户按下该按钮时,它将执行以下操作:

  1. 在工作表Eff上的数据透视表中按下按钮用户标记名称之前
  2. 按下按钮后,将在工作表Pivot_All的另一个数据透视表中过滤相同的名称

enter image description here

我尝试了这个,但是在.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

1 个答案:

答案 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