In the below code if the line in the else block runs it errors with "Application-defined or object-defined error".
This code is within a With block set to an Excel Application object automated from Acces. This code is part of a function that iteratively adds a pivottable to an Excel file. Through testing I know workseet(1) will always be a pivottable in my scenario if there is a pivot cache (although a way to identify the worksheet with the pivottable would be better).
The function is iteratively called and strTableName is based on a concatenation of a unique number so that it changes for each pivot table added. The purpose of the If statement and branching Else is to eliminate file bloat from adding multiple pivotcaches from the same source.
Any ideas of what I am missing?
This code is within a With block set to an Excel Application object automated from Acces. This code is part of a function that iteratively adds a pivottable to an Excel file. Through testing I know workseet(1) will always be a pivottable in my scenario if there is a pivot cache (although a way to identify the worksheet with the pivottable would be better).
The function is iteratively called and strTableName is based on a concatenation of a unique number so that it changes for each pivot table added. The purpose of the If statement and branching Else is to eliminate file bloat from adding multiple pivotcaches from the same source.
Any ideas of what I am missing?
Code:
If XLWorkBook.PivotCaches.Count = 0 Then
XLWorkBook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:= _
.Range(XLSheet.Range("A1"), XLSheet.Range("A1").SpecialCells(xlLastCell))).CreatePivotTable TableDestination:="", TableName:= _
strTableName
.ActiveSheet.PivotTableWizard TableDestination:=.ActiveSheet.Cells(3, 1)
Else
XLWorkBook.Worksheets(1).PivotTables( _
1).PivotCache.CreatePivotTable TableDestination:="", TableName _
:=strTableName
End If