2016-07-27 52 views
0

我試圖從表中獲取數據透視表數據並將值輸入到區域中。我可以獲取測試數據,但循環中的相同操作會導致1004的運行時錯誤。請參閱下面的代碼,並再次感謝大家的時間。祝你有個愉快的日子Getpivotdata循環導致運行時錯誤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 
+0

從單元格拉出來的'key'可能不是正確的類型嗎?或者在這些方面還有額外的空間或其他東西? – RGA

+1

是的你是對的。將初始測試值設置爲'key = Range(「G7」)。值在第一次測試時會出現相同的錯誤。所以這是問題產生的地方 – Matus

+0

好的,問題出在源代碼透視表中。我需要找到如何編寫它的方法,所以如果在數據透視表中找不到值,它會跳到下一個rcell。感謝您提供任何提示 – Matus

回答

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