The Project
I have a workbook that hosts weekly man-hour information. Everything is viewed and modified via a Userform
. On the Userform
I have a ListBox1
to show a PivotTableX
of the associated week, so that I can easily see what the daily and total overtime hours are for the week. On my Userform
I have two radio buttons that will alternate the PivotTableX
to show Total Hours or Overtime Hours.
The Problem
When I click the radio button, to change the PivotField
, I get an Error 1004
. I've done a fair amount of searching but I can't find a solution that works. I might not understand the code behind Pivot Tables enough to know when a solution is right in front of me.
The Code
The following is the code that raises the error:
Private Sub OptionButton1_Change()
Dim ws As Worksheet
Dim wsName As String
Dim pvtTable As PivotTable
Set ws = ThisWorkbook.Sheets(SelSheet())
ws.Select
Set pvtTable = ws.PivotTables("PivotTable" & ws.Index)
With pvtTable
If OptionButton1.Value = True Then 'Total Time
.AddDataField .PivotFields("TOTAL (W/O LUNCH)"), "Sum of TOTAL (W/O LUNCH)", xlSum
.PivotFields("Sum of PREMIUM TIME").Orientation = xlHidden
Else
.AddDataField .PivotFields("PREMIUM TIME"), "Sum of PREMIUM TIME", xlSum
.PivotFields("Sum of TOTAL (W/O LUNCH)").Orientation = xlHidden
End If
End With
End Sub
The .AddDataField
lines throw the error. It makes me think that my code isn't finding the Pivot Table on the worksheet. To combat this, instead of using a PivotTables()
index number, I call out for it specifically by name. When a new sheet is created, the Table and Pivot Table are created and numbered by the worksheet index. My worksheets will never change their index position as they are created in order from oldest to newest.
I also thought maybe the issue came from the sheet not being selected, as I've ran into similar issues with 1004 in the past, so I select the sheet but that did nothing.
Before you ask, SelSheet()
is a simple function to return the name of the sheet based on the selection in ComboBox4
(the combobox next to "Week"). I'll include the snippet at the end (it works, it's not the issue.)
I've verified that the proper worksheet is being selected and that the names of the Table and Pivot Table are also correct via Debug.Print
.
SelSheet() Function
Function SelSheet() As String
Dim ws As Worksheet
Dim wsName As String
wsName = ComboBox4.Value
Set ws = ThisWorkbook.Sheets(Replace(wsName, "/", ""))
SelSheet = ws.Name
End Function