我的任务是编写一个宏来复制和格式化初步数据透视表以适应公司的品牌风格。
基本宏已完成,但我无法根据其层次结构和依赖关系自动化数据透视表字段的格式化。
当前代码如下所示
Sub FormatHierarchy()
'formatting Hierarchy level 1
ActiveSheet.PivotTables(1).PivotSelect "'EBITDA category'[All]", _
xlLabelOnly + xlFirstRow, True
With Selection
With .Font
.Name = "Arial Narrow"
.Size = 10
.Bold = True
End With
.VerticalAlignment = xlTop
.HorizontalAlignment = xlLeft
.WrapText = True
End With
'formatting Hierarchy level 2
ActiveSheet.PivotTables(1).PivotSelect "Account[All]", _
xlLabelOnly + xlFirstRow, True
With Selection
With .Font
.Name = "Arial Narrow"
.Size = 10
.Bold = False
End With
.VerticalAlignment = xlTop
.HorizontalAlignment = xlLeft
.WrapText = True
.IndentLevel = 0
End With
'formatting Hierarchy level 3
ActiveSheet.PivotTables(1).PivotSelect "SuSa account[All]", _
xlLabelOnly + xlFirstRow, True
With Selection
With .Font
.Name = "Arial Narrow"
.Size = 10
.Bold = False
End With
.VerticalAlignment = xlTop
.HorizontalAlignment = xlLeft
.WrapText = True
.IndentLevel = 1
End With
End Sub
“EBITDA类别”,“帐户”和“SuSa帐户”将根据原始数据和经理决定调用它们而改变,因此我无法直接使用这些名称。 有没有办法根据字段名称的层次结构直接引用字段名称?
original pivot table
resulting pivot table(粗体为1级,普通级别为2级,缩进级别为3级)
感谢任何帮助。
谢谢!
答案 0 :(得分:0)
我没有100%成功地重新创建您的设置,但如果我理解正确,那么以下内容应该有所帮助:
示例代码:
Dim i as Long
For i = 1 to ActiveSheet.PivotTables(1).PivotFields.Count
If ActiveSheet.PivotTables(1).PivotFields(i).Position = 1 Then
'Enter your formatting for hirearchy level 1 here
ElseIf ActiveSheet.PivotTables(1).PivotFields(i).Position = 2
'Enter your formatting for hirearchy level 2 here
ElseIf ActiveSheet.PivotTables(1).PivotFields(i).Position = 3
'Enter your formatting for hirearchy level 3 here
End If
Next i
答案 1 :(得分:0)
尝试下面的代码,代码中的解释为注释:
Option Explicit
Sub FormatHierarchy()
Dim PvtTbl As PivotTable
Dim PvtFld As PivotField
' set the PivotTable object
Set PvtTbl = ActiveSheet.PivotTables(1)
' loop through all Pivot Fields in Pivot Table
For Each PvtFld In PvtTbl.PivotFields
Select Case PvtFld.Position
Case 1
' do your format here ...
Case 2
' do your format here ...
Case 3
' do your format here ...
End Select
Next PvtFld
End Sub