簡體   English   中英

基於字段層次結構的VBA數據透視表格式

[英]VBA pivot table formatting based on field hierarchy

我的工作是編寫一個宏,該宏將復制並格式化初步的數據透視表以適合公司范圍內的品牌風格。
基本宏已經完成,但是我無法根據它們的層次結構和依存關系自動設置樞軸字段的格式。

當前代碼如下所示

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帳戶”將根據原始數據以及經理決定調用它們的方式進行更改,因此我無法直接使用這些名稱。 有沒有一種方法可以根據其層次結構直接引用字段名稱?

原始數據透視表
結果數據透視表 (粗體為1級,普通為2級,縮進為3級)

任何幫助表示贊賞。
謝謝!

我沒有100%成功地重新創建您的設置,但是如果我正確理解它,那么以下內容應該會有所幫助:

  1. 編寫遍歷每個PivotFields的函數(類似於PivotSelect,但是使用Index而不是name作為引用)。
  2. 使用PivotField的“位置”屬性標識層次結構中的級別
  3. 使用IF語句根據上面確定的級別進行格式化

示例代碼:

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

嘗試下面的代碼,並在代碼中以注釋的形式進行解釋:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM