I have a workbook with 70 plus sheets. Each sheet is created and named, and I put corresponding data into the worksheet using filters. The data range has potential to change week to week. I have written a vba program to do everything but create pivot tables within each worksheet using the unique filtered data. My question is, how do I create a pivot table within each worksheet inside the for loop? I have deducted that the problem in my code below is the source data section in the code. The data range for each tab will be different(columns stay same but number of rows will differ). Do I also need to rename the pivot tables as they iterate within the loop?
Sub Ptloop()
dim x as long
dim SorceRange as Range
dim k as long
'start of first generated work sheet
x=4
'number of worksheets
k=75
Set SourceRange = Range("A4", ActiveCell.End(xlDown).End(xlToRight))
For Each Worksheet In ActiveWorkbook.Sheets
If x <= k Then
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
Sheets(x).SourceRange, Version:=xlPivotTableVersion14). _
CreatePivotTable TableDestination:=Sheets(x).Cells(4, 21), TableName:="PivotTable3", DefaultVersion _
:=xlPivotTableVersion14
x = x + 1
Else
Exit For
End If
Next Worksheet
End Sub
SourceRangeset inside theFor Loopand qualify it to thews. SoSet SourceRange = Worksheet.Range("A4", Worksheet.Range("A4")l.End(xlDown).End(xlToRight)). You can name each PT withPivoTable & x, if you want them to be different. It's not necessary though, if they are all on different sheets. - Scott Holtzman