2016-11-22 142 views
0

我嘗試運行下面的代碼時出現錯誤。任何人都可以請解釋爲什麼當代碼嘗試創建數據透視表時,爲什麼在最後一部分出現錯誤?在VBA中創建數據透視表時出錯

錯誤說:「無效的過程調用或參數」當我設置PVT

Private Sub CommandButton1_Click() 

Dim sht As Worksheet 
Dim pvtCache As PivotCache 
Dim pvt As PivotTable 
Dim StartPvt As String 
Dim SrcData As String 

For Each PT In Sheet5.PivotTables 
    PT.TableRange2.Clear 
Next PT 

'Determine the data range you want to pivot 
    SrcData = ActiveSheet.Name & "!" & Range("B7:D10").Address(ReferenceStyle:=xlR1C1) 

'Where do you want Pivot Table to start? 
    StartPvt = Sheet5.Name & "!" & Sheet5.Range("B12").Address(ReferenceStyle:=xlR1C1) 

'Create Pivot Cache from Source Data 
    Set pvtCache = ActiveWorkbook.PivotCaches.Create(_ 
    SourceType:=xlDatabase, _ 
    SourceData:=SrcData) 

MsgBox StartPvt & "_" & SrcData 

'Create Pivot table from Pivot Cache 
    Set pvt = pvtCache.CreatePivotTable(_ 
    TableDestination:=StartPvt, _ 
    TableName:="TestPivotTable") 

End Sub 
+0

錯誤發生的確切線是什麼?那錯誤信息是什麼意思? – rohrl77

+0

錯誤說:「無效的過程調用或參數」在我設置pvt的最後部分。 –

回答

2

的最後一部分,我認爲你的代碼正在努力處理SrcDataStartPvt,因爲它是期待一個被存儲爲字符串範圍。 這和你的完全一樣,但它將範圍存儲爲Range s,並僅在需要時纔將它們轉換爲字符串。

Private Sub CommandButton1_Click() 

    Dim sht As Worksheet 
    Dim pvtCache As PivotCache 
    Dim pvt As PivotTable 
    Dim SrcData As Range, StartPvt As Range 
    Dim PT As Variant 

    For Each PT In Sheet5.PivotTables 
     PT.TableRange2.Clear 
    Next PT 

    'Determine the data range you want to pivot 
     Set SrcData = ActiveSheet.Range("B7:D10") 

    'Where do you want Pivot Table to start? 
     Set StartPvt = Sheet5.Range("B12") 

    'Create Pivot Cache from Source Data 
     Set pvtCache = ActiveWorkbook.PivotCaches.Create(_ 
     SourceType:=xlDatabase, _ 
     SourceData:=SrcData.Address) 

    MsgBox StartPvt.Parent.Name & "!" & StartPvt.Address(ReferenceStyle:=xlR1C1) & "_" & _ 
      SrcData.Parent.Name & "!" & SrcData.Address(ReferenceStyle:=xlR1C1) 

    'Create Pivot table from Pivot Cache 
     Set pvt = pvtCache.CreatePivotTable(_ 
     TableDestination:=StartPvt, _ 
     TableName:="TestPivotTable") 

End Sub