2017-05-09 54 views
0
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.698VBA數字格式不起作用

+1

請仔細閱讀[問],然後[編輯]你的問題來改善它。至少包括解釋你的代碼實際做了什麼以及你期望它做什麼(你想要的結果)。只是張貼代碼而不問任何問題是非常糟糕的做法。 –

+0

是'Range(「B43:AJ5000」)'是否應該是'PivotTable'的範圍? –

+0

我同意你的意見。我應該更多地解釋。此代碼僅顯示數據透視表中的美元成本。是的,這是數據透視表的風靡。在此先感謝 – user3860954

回答

2

下面witl格式的代碼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 
+0

謝謝!這是完美的。 FormatProj和Zero是用於格式化數字/顏色等的單獨代碼。 – user3860954

+0

@ user3860954歡迎您,請點擊我答案旁邊的灰色複選標記(它會變成綠色),標記爲「答案」,您將獲得+2點 –