ASKER
ASKER
ASKER
ASKER
ASKER
Option Explicit
Sub ChangeHeaddings()
Dim WSd As Worksheet
Dim WSp As Worksheet
Dim I As Long
Dim pvtField As PivotField
Dim pvt As PivotTable
Dim sHeader As String
Dim vHeader As Variant, vParts As Variant
'---> Disable Events
With Application
.EnableEvents = False
.DisplayAlerts = False
.ScreenUpdating = False
End With
'---> Set Variables
Set WSd = Sheets("Data")
Set WSp = Sheets("Pivot")
sHeader = "This_Year_Month ,Last_Year_Month ,This_Year_3Months ,Last_Year_3Months ,This_Year_12Months ,Last_Year_12Months "
vHeader = Split(sHeader, ",")
Set pvt = WSp.PivotTables(1)
'---> Change Header
For Each pvtField In pvt.DataFields
For I = LBound(vHeader) To UBound(vHeader)
If pvtField.Name = vHeader(I) Then
vParts = Split(pvtField.Name, "_")
If InStr(LCase(pvtField.Name), "this") <> 0 Then
pvtField.Caption = Year(WSd.Range("E3")) & " " & vParts(2)
Else
pvtField.Caption = Year(WSd.Range("E3")) - 1 & " " & vParts(2)
End If
Exit For
End If
Next I
Next pvtField
'---> Refresh Pivot
For I = 1 To WSp.PivotTables.Count
WSp.PivotTables(I).RefreshTable
Next I
'---> Enable Events
With Application
.EnableEvents = True
.DisplayAlerts = True
.ScreenUpdating = True
End With
MsgBox "Fields changed successffully. Please check Pivot tables.", vbInformation, "Pivot Field Change"
End Sub
Sub ResetHeaddings()
Dim WSd As Worksheet
Dim WSp As Worksheet
Dim I As Long
Dim pvtField As PivotField
Dim pvt As PivotTable
Dim sHeader As String
Dim vHeader As Variant, vParts As Variant
'---> Disable Events
With Application
.EnableEvents = False
.DisplayAlerts = False
.ScreenUpdating = False
End With
'---> Set Variables
Set WSd = Sheets("Data")
Set WSp = Sheets("Pivot")
sHeader = "This_Year_Month ,Last_Year_Month ,This_Year_3Months ,Last_Year_3Months ,This_Year_12Months ,Last_Year_12Months "
vHeader = Split(sHeader, ",")
Set pvt = WSp.PivotTables(1)
'---> Change Header
For Each pvtField In pvt.DataFields
If IsNumeric(Left(pvtField.Name, 4)) Then
pvtField.Caption = vHeader(I)
I = I + 1
End If
Next pvtField
'---> Refresh Pivot
For I = 1 To WSp.PivotTables.Count
WSp.PivotTables(I).RefreshTable
Next I
'---> Enable Events
With Application
.EnableEvents = True
.DisplayAlerts = True
.ScreenUpdating = True
End With
MsgBox "Fields changed successffully. Please check Pivot tables.", vbInformation, "Pivot Field Change"
End Sub
ASKER
ASKER
ASKER
ASKER
ASKER
Microsoft Excel topics include formulas, formatting, VBA macros and user-defined functions, and everything else related to the spreadsheet user interface, including error messages.
TRUSTED BY