循环中的Getpivotdata导致运行时错误1004

时间:2016-07-27 11:55:11

标签: excel vba

我试图从表中获取数据透视表数据并将值输入到区域中。我可以在测试中获取数据,但循环中的相同操作会导致运行时错误1004.请参阅下面的代码,并再次感谢大家的时间。祝你有愉快的一天

Sub Pivot3()

Dim targetregion As Range
Dim pt As PivotTable
Dim rCell As Range
Dim key As Variant
Dim test As Variant

Set pt = Workbooks("OPEX.xlsm").Worksheets("Opex_main").PivotTables("PivotTable1")
Set targetregion = Range("J2:J19")


'testing whether I can get pivot data
key = 71010080
test = pt.GetPivotData("SumOfValues", "CC_Grouping", "xyz", "GL", key)
MsgBox test
'end of test, all good here

For Each rCell In targetregion
        If rCell.HasFormula Then

        Else
            key = Cells(rCell.Row, 7).Value
            MsgBox key  ' testing if key was properly loaded for the row, all good here

            'here the problem occurs, yet it is same as few lines up
            test = pt.GetPivotData("SumOfValues", "CC_Grouping", "xyz", "GL", key)

            MsgBox test  'testing if correct value was loaded from pivot table
            rCell.Value = test
        End If
Next rCell


End Sub

1 个答案:

答案 0 :(得分:0)

解决。至少它按预期行事,到目前为止没有出现任何错误。 Err.Clear在循环中,所以它在第二次命中运行时错误1004时,它能够将它加载到Err中。这就是我的理解

Sub Pivot3()

Dim targetregion As Range
Dim pt As PivotTable
Dim rCell As Range
Dim key As Variant
Dim test As Variant
Dim group As Variant

Set pt = Workbooks("OPEX.xlsm").Worksheets("Opex_main").PivotTables("PivotTable1")
Set targetregion = Range("J2:J19")


group = Range("A7")
For Each rCell In targetregion
        If rCell.HasFormula Then

            Else
                    Err.Clear
                    key = Cells(rCell.Row, 7).Value
                    On Error Resume Next                        
                    rCell.Value = pt.GetPivotData("SumOfValues", "CC_Grouping", group, "GL", key)

        End If

Next rCell

End Sub