简体   繁体   中英

VBA code runs successfully only once

I am trying to run the below code and it runs fine and does the job but only once. Then it starts throwing the run time error 1004: application or object defined error. Context: I have about 15 pivot tables across 10 worksheets to be updated weekly. I change the source data every week and I want the pivot tables to be updated.

Sub UpdateReports()

Dim wb As Workbook
Dim PT As PivotTable, PTCache As PivotCache, newPT As PivotTable

Set wb = Application.Workbooks("Open items VIM Analytics September 16th, 2016.xlsx")
Set PTCache = wb.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=wb.Worksheets("Vim open items 09.09.2016").Range("a:au"))
Set PT = wb.Worksheets("Per Location").PivotTables("PivotTable3")
Set newPT = wb.Worksheets("Per Location").PivotTables.Add(PivotCache:=PTCache, TableDestination:=wb.Worksheets("Per Location").Range("a200"))

PT.CacheIndex = newPT.CacheIndex

End Sub

I am getting the error on

Set newPT = wb.Worksheets("Per Location").PivotTables.Add(PivotCache:=PTCache, TableDestination:=wb.Worksheets("Per Location").Range("a200"))

If this falls on the line

Set newPT = wb.Worksheets("Per Location").PivotTables.Add(PivotCache:=PTCache, TableDestination:=wb.Worksheets("Per Location").Range("a200"))

It can not create a pivot table because it already has the same name. I suggest to try to explicitly specify the name or remove before adding the old table.

You can still try to link the old table with the new cache.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM