I would like a VBA code that allows me to dynamically change a formula's range to the last row of data for a pivot table. The formula is stored in Command Text under Definition under Connection Properties in Queries & Connections. Sub UpdatePivotTableDataSource()
Dim ws As Worksheet
Dim pivotSheet As Worksheet
Dim lastRow As Long
Dim conn As WorkbookConnection
Dim cmdText As String
Dim pt As PivotTable
enter image description here
The current code I attached has a Run-time error 1004 at line: "conn.OLEDBConnection.CommandText = cmdText"
Thanks in advance!
' Set the worksheet and find the last row of data in "Billing Analysis " sheet
Set ws = ThisWorkbook.Sheets("Billing Analysis ")
lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).row
' Update the CommandText in the connection properties
cmdText = "'Billing Analysis '!$A$1:$AA$" & lastRow
' Locate the connection for the Pivot Table and update the command text
For Each conn In ThisWorkbook.Connections
If conn.Name = "WorksheetConnection_Billing Analysis !$A$1:$bw$30000" Then ' Adjust to your connection's exact name
conn.OLEDBConnection.CommandText = cmdText
Exit For
End If
Next conn
' Refresh PivotTable5 on "No. of Billings-by Service" sheet
Set pt = ThisWorkbook.Sheets("No. of Billings-by Service").PivotTables("PivotTable5")
pt.RefreshTable
MsgBox "PivotTable5 has been updated with the new data range and refreshed!"
End Sub
I expect the code to dynamically change the formula range of the pivot table to include up to the last row of data in a scenario that the datasource overshoots the current range.