I am attempting to loop though the first column on a worksheet and use those values as report filters for a pivot table on another worksheet. However, I am getting
run-time error 1004 "Application-defined or object-defined error"
when I run the following code.
Dim sh As Worksheet
Dim rw As Range
Dim RowCount As Integer
Dim ThisItem As String
Dim pt As PivotTable
RowCount = 0
Set pt = Worksheets("MySheet").PivotTables("MyPivot")
Set sh = Worksheets("LoopSource")
For Each rw In sh.Rows
If sh.Cells(rw.Row, 1).Value = "" Then
Exit For
Else:
' Set the current item name as a variable
ThisItem = sh.Cells(rw.Row, 1).Value
' Filter the pivot table on the value
With pt
.PivotFields("FilterField").ClearAllFilters
.PivotFields("FilterField").CurrentPage = ThisItem
.RefreshTable
End With
' Print the pivot table to PDF
Call Module1.PrintPDF(ThisItem)
End If
RowCount = RowCount + 1
Next rw
It fails on this line:
.PivotFields("FilterField").CurrentPage = ThisItem
If I hard-code a value like this it works:
.PivotFields("FilterField").CurrentPage = "Criterion"
Likewise, it also works if instead of setting ThisItem to the cell value, I do something like
ThisItem = "Criterion"
I do not understand the reason for the error, since ThisItem is a string variable. What am I missing? Thank you for your help.