2014-11-06 208 views
0

我無法找到我的運行時錯誤424的根本原因。我知道這是與一個缺失的對象有關,但我不確定哪裏或哪個對象甚至會在這種情況下。我的假設是與ActiveSheet有關,但我有點失落。Excel宏運行時錯誤424

Sub Macro1() 
' 
' Macro1 Macro 
' 

' 
Sheets.Add 

錯誤這裏就從這裏開始

PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _ 
    ActiveSheet.Range("A1").CurrentRegion.Select, Version:= _ 
    xlPivotTableVersion12).CreatePivotTable TableDestination:="Sheet1!R3C1", _ 
    TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion12 

錯誤結束

Sheets("Sheet1").Select 
Cells(3, 1).Select 

With ActiveSheet.PivotTables("PivotTable1").PivotFields("Source Type") 
    .Orientation = xlRowField 
    .Position = 1 

End With 

With ActiveSheet.PivotTables("PivotTable1").PivotFields("Category") 
    .Orientation = xlRowField 
    .Position = 2 

End With 

ActiveSheet.PivotTables("PivotTable1").PivotFields("Category").Orientation = _ 
    xlHidden 

With ActiveSheet.PivotTables("PivotTable1").PivotFields("Activity") 
    .Orientation = xlRowField 
    .Position = 2 

End With 

ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables(_ 
    "PivotTable1").PivotFields("USD Amount"), "Sum of USD Amount", xlSum 
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables(_ 
    "PivotTable1").PivotFields("Quantity"), "Sum of Quantity", xlSum 

End Sub 

回答

0

我很少需要創建透視表編程如此,讓這是怎麼回事我創建了一個小分來逐步瞭解:

Sub CreatePivotOnNewSheet() 
Sheets.Add 
ActiveSheet.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _ 
    ActiveSheet.Range("A1").CurrentRegion, Version:= _ 
    xlPivotTableVersion12).CreatePivotTable TableDestination:="Sheet1!R3C1", _ 
    TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion12 
End Sub 

This compiles OK but throws an error 438: Object doesn't support this property or method. I searched the Object Browser for PivotCaches and found that it is a member of Workbook and PivotTable. It isn't a member of Worksheets! This makes sense when you consider that pivot tables on different sheets can use the same pivot cache.

所以,改變代碼:

Sub CreatePivotOnNewSheet() 
Sheets.Add 
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _ 
    ActiveSheet.Range("A1").CurrentRegion, Version:= _ 
    xlPivotTableVersion12).CreatePivotTable TableDestination:="Sheet1!R3C1", _ 
    TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion12 
End Sub 

,現在我們得到一個運行時錯誤:

no data for pivot table

哪個需要更大才能顯示完整的原因(謝謝微軟!),但我想它繼續說對至少包含兩行的範圍的引用,並且其頂部行中沒有空白單元格。在中斷模式下,我去了新添加的工作表並創建了一個2x2的數據表。回到IDE中,按下F8並且它工作正常,儘管數據透視表沒有定義任何行/列等。我沒有試圖測試你的剩餘代碼,這似乎創造了定義 - 我會把它留給你。

0

它與錄製的宏的問題,有沒有在所有定義的對象。

我建議用變量替換所有「活動」短語。這裏是開始:

Dim wb As Workbook 
Set wb = ActiveWorkbook 

Dim ws1 As Worksheet, ws2 As Worksheet 

Set ws1 = wb.Sheets(1) 
Set ws2 = wb.Sheets(2) 

Dim Caches As PivotCache 


Set Caches = wb.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _ 
    ws2.Range("A1:C3"), Version:= _ 
    xlPivotTableVersion12)