数据透视表数据范围的VBA数字格式不起作用

时间:2017-05-09 14:38:20

标签: excel-vba vba excel

Sub Cost()

    Dim CurrentPivot As String

    On Error GoTo OnError

    Expand

    CurrentPivot = ActiveSheet.Name

    ActiveSheet.PivotTables(CurrentPivot).PivotFields("Sum of Hours"). _
        Orientation = xlHidden
    ActiveSheet.PivotTables(CurrentPivot).AddDataField ActiveSheet.PivotTables( _
        CurrentPivot).PivotFields("Cost"), "Sum of Cost", xlSum
    FormatProj
    Zero
    Range("B43:AJ5000").Select
    Selection.NumberFormat = "$#,##0.00;[Red]$#,##0.00"

OnError:
    MsgBox ("Viewing data in $Cost")

    ActiveWorkbook.ShowPivotTableFieldList = False
    Range("B44").Select

End Sub

我的号码仍然是2615233.698

1 个答案:

答案 0 :(得分:2)

下面的代码将PivotTable的范围格式化为您想要的格式。

您可以直接访问数据透视表的范围,并使用以下命令修改其格式,而不是使用Range("B43:AJ5000").Select和更晚Selection

PvtTbl.TableRange2.NumberFormat = "$#,##0.00;[Red]$#,##0.00"

<强>代码

Option Explicit

Sub Cost()

Dim CurrentPivot As String
Dim PvtTbl      As PivotTable

On Error GoTo OnError
'Expand ' <-- not sure what does this Sub-routine actually does

CurrentPivot = ActiveSheet.Name

' set the Pivot-Table object
Set PvtTbl = ActiveSheet.PivotTables(CurrentPivot)
With PvtTbl
    .PivotFields("Sum of Hours").Orientation = xlHidden
    .AddDataField .PivotFields("Cost"), "Sum of Cost", xlSum

    'FormatProj ' <-- not sure what does this Sub-routine actually does
    'Zero ' <-- not sure what does this Sub-routine actually does

    .TableRange2.NumberFormat = "$#,##0.00;[Red]$#,##0.00"
End With

OnError:
MsgBox "Viewing data in $Cost"

ActiveWorkbook.ShowPivotTableFieldList = False
Range("B44").Select

End Sub
相关问题