I am trying to put a pivot table in my macro, but each week, the amount of data I have will change. My data that UI want to use is in columns A to E. How do I select all of the data in columns A to E if my row amount varies.
Here's a sample of code that I have used more than once...
Dim WSD As Worksheet, WSD2 As Worksheet
Dim PTCache As PivotCache
Dim PT As PivotTable, PTbl As PivotTable
Dim PRange As Range
Dim LastRow As Long
Set WSD = Worksheets("Main Data")
Set WSD2 = Worksheets("Pivot Detail")
vFields = Range("Table_PivotData").Value
'define input area and set up a Pivot Cache
LastRow = WSD.Cells(65536, 1).End(xlUp).Row
WSD.Cells(1, 1).Resize(LastRow, 37).Select
ActiveWorkbook.Names.Add Name:="PData", RefersTo:=Selection
Set PRange = WSD.Cells(1, 1).Resize(LastRow, 37)
Set PTCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, Range("PData"))
Set PT = PTCache.CreatePivotTable(WSD2.Range("A10"), "Detail Pivot")
PT.ManualUpdate = True
'...continue to play with the pivot table
This is the beginning of code that works with about 40 fields, so I put the fields in a table and loaded them into an array to simplify referencing them. The bottom line is to create the range name on the fly, and use that as the data source for the pivot table.