2016-08-19 178 views
1

我一直在創建數據透視表時調試了幾個小時的代碼,但不幸的是,我無法找出問題所在。它不斷顯示,Object doesn't support this property or method.創建數據透視表時出錯

Sub CreatePivotTable() 

Dim sht, srcSheet As Worksheet, ccsheet As Worksheet 
Dim pvtCache As PivotCache 
Dim pvt As PivotTable 
Dim StartPvt As String 
Dim SrcData As String 
Dim lrow As Long 
Set srcSheet = ThisWorkbook.Sheets("Document Raw") 
lrow = srcSheet.Cells(Rows.Count, 1).End(xlUp).Row + 1 
Set ccsheet = ThisWorkbook.Sheets("Character Count") 

SrcData = srcSheet & "!" & Range("A1:V"& lrow).Address(ReferenceStyle:=xlR1C1)' this is the line that errors 

StartPvt = ccsheet & "!" & ccsheet.Range("A79").Address(ReferenceStyle:=xlR1C1) 

Set pvtCache = ActiveWorkbook.PivotCaches.Create(_ 
SourceType:=xlDatabase, _ 
SourceData:=SrcData) 

Set pvt = pvtCache.CreatePivotTable(_ 
TableDestination:=StartPvt, _ 
TableName:="PivotTable1") 

End Sub 

任何幫助嗎?由於

+0

有它突出的是一個問題,一個特定的行? – Clusks

+0

@Clusks這是'SrcData = srcSheet&「!」這行' &Range(「A1:V」&lrow).Address(ReferenceStyle:= xlR1C1)'這是錯誤的那一行 ' – ramj

+0

你試過替換&「!」 &with。? – Clusks

回答

0

嘗試下面的修改後的代碼(我喜歡設置了Range,後來PivotCachePivotTable這種方法):

Sub CreatePivotTable() 

Dim srcSheet    As Worksheet 
Dim ccSheet     As Worksheet 
Dim pvtCache    As PivotCache 
Dim pvtTbl     As PivotTable 
Dim StartPvt    As Range 
Dim SrcData     As Variant 
Dim lrow     As Long 

Set srcSheet = ThisWorkbook.Sheets("Document Raw") 
lrow = srcSheet.Cells(srcSheet.Rows.Count, 1).End(xlUp).Row 
Set ccSheet = ThisWorkbook.Sheets("Character Count") 

' make sure you have valid data from Column A to Column V 
Set SrcData = srcSheet.Range("A1:V" & lrow) 
Set StartPvt = ccSheet.Range("A79") 

'Create Pivot table from Pivot Cache 
Set pvtCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, SrcData) 


' add this line in case the Pivot table doesn't exit >> first time running this Macro 
On Error Resume Next 
Set pvtTbl = ccSheet.PivotTables("PivotTable1") ' check if "PivotTable1" Pivot Table already created (in past runs of this Macro) 

On Error GoTo 0 
If pvtTbl Is Nothing Then 
    Set pvtTbl = ccSheet.PivotTables.Add(PivotCache:=pvtCache, TableDestination:=StartPvt, TableName:="PivotTable1") 
Else 
    pvtTbl.ChangePivotCache pvtCache 
    pvtTbl.RefreshTable 
End If 

End Sub 
+0

此行返回類型不匹配錯誤'Set pvtCache = ActiveWorkbook.PivotCaches.Add(xlDatabase,SrcRng)' – ramj

+0

打開了多少個工作簿? –

+0

只有一個工作簿。 – ramj