Excel VBA – 格式化数据透视表(.NumberFormat)不起作用

目的

创build一个拉入规范化数据集的macros。 将数据集放入数据透视表中以便于解释。

APPROACH

  1. 规范化数据
  2. select标准化数据并创build数据透视表
  3. configuration数据透视表标题和列
  4. 格式标题和列

Sub createPivot() Dim ws As Worksheet Dim pvtCache As pivotCache Dim pvt As pivotTable Dim srcData As String Dim lastRow As Long Dim startPvt As String Dim target As Worksheet 'Delete previous pivottable Worksheets("PIVOT").PivotTables("PivotTable1").TableRange2.Clear 'Select pivot table data Worksheets("CONSOLIDATED").Activate Set ws = ActiveSheet lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row srcData = ActiveSheet.Name & "!" & Range("A1:H" & lastRow).Address(ReferenceStyle:=xlR1C1) 'Set pivot table location Set target = ThisWorkbook.Worksheets("PIVOT") startPvt = target.Name & "!" & target.Range("A1").Address(ReferenceStyle:=xlR1C1) 'Create pivot cache Set pvtCache = ActiveWorkbook.PivotCaches.Create( _ SourceType:=xlDatabase, _ SourceData:=srcData) 'Deploy pivot table Set pvt = pvtCache.CreatePivotTable( _ TableDestination:=startPvt, _ TableName:="PivotTable1") 'Add Pivot Fields pvt.PivotFields("Fiscal Year").Orientation = xlColumnField pvt.PivotFields("Fiscal Year").Position = 1 pvt.PivotFields("Fiscal Month").Orientation = xlColumnField pvt.PivotFields("Fiscal Month").Position = 2 pvt.PivotFields("Unit").Orientation = xlRowField pvt.PivotFields("Unit").Position = 1 pvt.PivotFields("Project").Orientation = xlRowField pvt.PivotFields("Project").Position = 2 pvt.PivotFields("Base Expense").Orientation = xlDataField 'Format cells pvt.PivotFields("Base Expense").NumberFormat = "$ #,##0" End Sub 

问题

  • 没有错误抛出,但是pvt.PivotFields("Base Expense").NumberFormat = "$ #,##0"似乎不起作用。

质询

  1. 我不确定为什么VBA不会抛出错误,但是在给定正确的参数时拒绝格式化表格。 任何帮助表示赞赏

我前一阵子写了这个macros来格式化我的数据透视表。 修改代码以适应您的需求应该相当容易。 它遍历每个值字段并更改函数以对值进行求和和格式化。

 Sub formatPivot() Dim pvtTbl As PivotTable Dim pvtName As String Dim pvtType As String Dim pvtFld As PivotField pvtName = ActiveCell.PivotTable.Name ' Get the name of the active pivottable Set pvtTbl = ActiveSheet.PivotTables(pvtName) ' set the pivot table to the active table ' Change to sum and update the number format For Each pvtFld In pvtTbl.DataFields pvtType = pvtFld With pvtTbl.PivotFields(pvtType) .Function = xlSum .NumberFormat = "#,##0" End With Next End Sub