I tried to find a previous QA on this, but I haven't been able to find a solution.
I have inherited a connected Excel spreadsheet that has one worksheet that contains a slicer with about 170 different items on it. In this case they are employee names.
The next worksheet is a scorecard, that is populated by values from 4 different pivot tables.
So you select an employee in the slicer, the pivot tables filter to the info for that employee, and the information displays on the formatted scorecard.
Currently, the process is to click each employee on the slicer, one at a time, then go to the scorecard worksheet, print to pdf, and then save the pdf with the file name being the employee's name.
What I am wanting to do is use VBA to automate this process by clicking one button, it will loop through the slicer, select each employee, print to pdf the associated scorecard, and save the file in a directory on my PC using a cell with the employee's name as the file name.
I found some code on a previous QA on this site that I have been trying to adapt for this purpose.
It seems like it is working somewhat as it will correctly save a PDF of the first employee. When it is supposedly going to the next slicer item, it throws an error which is basically (not exact wording) '"we couldn't complete the action for the PivotTable" "in the sheet" "because there's already a PivotTable".
I can't figure out how to fix this error. All 4 pivot tables are on the same worksheet, and are side by side with at least one column in between them. I cycled through the slicer, and all items seem to have the same number of columns. The pivots only show one employee at a time.
Any ideas?
Sub LoopThroughSlicerAndPrintPDF()
Dim wsPrint As Worksheet
Dim wsSlicer As Worksheet
Dim slicerCache As slicerCache
Dim slicerItem As slicerItem
Dim pdfPath As String
Dim pdfName As String
Dim cellValue As String
' Set your worksheets
Set wsSlicer = ThisWorkbook.Sheets("Choose_an_Employee")
Set wsPrint = ThisWorkbook.Sheets("Scorecard")
' Set your slicer cache
Set slicerCache = ThisWorkbook.SlicerCaches("Slicer_Employee_Full_Name1")
' Loop through each slicer item
For Each slicerItem In slicerCache.SlicerItems
' Select the slicer item
slicerItem.Selected = True
' Get the value from the cell to name the PDF
cellValue = wsPrint.Range("C4").Value ' Change "A1" to your specific cell
' Define the PDF path and name
pdfName = cellValue & ".pdf"
pdfPath = "C:\Scorecards" & pdfName
' Print the worksheet to PDF
wsPrint.ExportAsFixedFormat Type:=xlTypePDF, Filename:=pdfPath, Quality:=xlQualityStandard
' Deselect the slicer item
slicerItem.Selected = False
Next slicerItem
End Sub