I am creating a VBA macro. Among other things, it makes a pivot table:
ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=Sheets("Working").UsedRange).CreatePivotTable TableDestination:="", TableName:="HDPivotTable", DefaultVersion:=xlPivotTableVersion10
This works, but when I delete all data from the Excel spreadsheet and replace it with new data of the same structure, I get an error on the above line:
Run-time error '13': Type mismatch
Could you please help me on this?
Thanks.
EDITED:
After applying Scott's suggestion, I get another error:
With Worksheets("Working")
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
lColumn = .Range("A" & .Columns.Count).End(xlToLeft).Column
ActiveWorkbook.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=.Range(.Cells(1, 1), .Cells(lRow, lColumn))).CreatePivotTable TableDestination:="", TableName:="HDPivotTable", DefaultVersion:=xlPivotTableVersion10
End With
ActiveSheet.Name = "HD Pivot"
ActiveSheet.PivotTableWizard TableDestination:=ActiveSheet.Cells(1, 1)
ActiveSheet.PivotTables("HDPivotTable").AddFields RowFields:="Location Code"
The error is: Run-time error '1004': AddFields method of PivotTable class failed
TableName
random/unique each time you run the code? – Kazimierz Jawor