2017-09-14 122 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引用。如果不需要,那么尝试没有它... –