2017-09-14 54 views
0

我遇到了數據透視表的問題。出於某種原因,這段代碼今天早上工作,但現在不是。這是我的代碼,直到錯誤。VBA代碼使數據透視表不能正常工作

Dim WSD2 As Worksheet 

Set WSD2 = ActiveWorkbook.Sheets.Add(After:= _ 
      Worksheets(Worksheets.Count)) 
    WSD2.Name = "POS Info" 


'-------------------------------------------------- 

'  Step 2: Create the pivot table 

'-------------------------------------------------- 

Dim WSD As Worksheet 
Dim PTCache As PivotCache 
Dim PT As PivotTable 
Dim PRange As Range 
Dim FinalRow As Long 
Dim FinalCol As Long 
Dim StartPT As String 
Dim BottomRowStart As Range ' this is for pivot table 
Dim BottomRowEnd As Range ' this is for pivot table 
Set WSD = Worksheets("aggregateData") 




' Select the data for pivot table 

FinalRow = WSD.Cells(Rows.Count, 2).End(xlUp).Row 
FinalCol = WSD.Cells(1, Columns.Count).End(xlToLeft).Column 
Set PRange = WSD.Cells(2, 1).Resize(FinalRow, FinalCol) 
Set PTCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PRange, Version:=xlPivotTableVersion14) 

'Where do I want the pivot table to start 

StartPT = WSD2.Range("A1").Address(ReferenceStyle:=xlR1C1) 

Set WSD2 = Worksheets("POS Info") 

'Begin to Create the Pivot Table 

Set PT = PTCache.CreatePivotTable(TableDestination:=StartPT, TableName:="POS Data") 

最後一行是從哪裏獲得以下錯誤消息:

「應用程序定義或對象定義的錯誤」。

任何幫助將不勝感激。

謝謝,

ģ

+1

據我所知,'TableDestination'必須是'Range',而不是地址。 – GSerg

回答

0

像@GSerg說,在評論,TableDestination需要一個範圍而不是一個地址。

現在你給TableDestination分配一個地址,它實際上只是一個字符串(文本),表示「$ A $ 3」或類似。您需要將其更改爲TableDestination:=WSD2.range(StartPT),然後您的代碼應該可以工作。

請注意,這可能以前工作,但沒有更多,因爲您可能已添加更多的工作表到文檔。然後,當VBA試圖瞭解地址「$ A $ 3」時,它無法決定使用哪個工作表,並因此引發錯誤。因此,在引用範圍時要非常明確,並通過workbook.worksheets路徑來完成。有關更多信息,請參見here

+0

Hey Burge和Serg,我仍然收到一條錯誤消息,說「Object_worksheet的」方法範圍「失敗」。有什麼建議麼? – GCC

+0

你的地址可能很奇怪。嘗試使用f8逐步完成代碼。一旦您爲StartPT分配了值,將鼠標懸停在其上以查看分配的值是什麼。它應該是一個地址字符串。請參閱此處瞭解更多信息:https://stackoverflow.com/questions/20008033/vba-method-range-of-object-worksheet-failed-suddenly-coming-up-when-running-c –

+0

另外,可能是您的R1C1引用。如果不需要,那麼嘗試沒有它... –