Excel VBA数据透视表 – 将数字格式化为百分数而不移动十进制

我想将数据透视表中的值转换为“0.0%”格式,而不移动小数,例如1 – > 1%,而不是100%。

我正在使用的代码在我的VBA数据透视表macros中产生一个“运行时错误”1004“:无法更改数据透视表报表的这一部分”错误。 代码是:

Sub Cost_Pivot() NoOfOutputRows = Worksheets("Sheet1").Range("A65536").End(xlUp).Row NoOfCols = Worksheets("Sheet1").Cells(1, Columns.Count).End(xlToLeft).Column ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:="Sheet1!R1C1:R" & NoOfOutputRows & "C" & NoOfCols, Version:=xlPivotTableVersion12).CreatePivotTable _ TableDestination:="Sheet2!R1C1", TableName:="PivotTable1", DefaultVersion _ :=xlPivotTableVersion12 Sheets("Sheet2").Select Cells(1, 1).Select With ActiveSheet.PivotTables("PivotTable1").PivotFields("Metric") .Orientation = xlRowField .Position = 1 End With With ActiveSheet.PivotTables("PivotTable1").PivotFields("CAM") .Orientation = xlRowField .Position = 2 End With With ActiveSheet.PivotTables("PivotTable1").PivotFields("CAM") .Orientation = xlColumnField .Position = 1 End With ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables("PivotTable1").PivotFields("Quantification"), "Sum of Quantification", xlSum Range("A2").Select ActiveSheet.PivotTables("PivotTable1").CompactLayoutRowHeader = "Metric" Range("B1").Select ActiveSheet.PivotTables("PivotTable1").CompactLayoutColumnHeader = "CAM" ActiveSheet.PivotTables("PivotTable1").ColumnGrand = False For Each ce In ActiveSheet.Range(Cells(1, 1), Cells(100, 100)) If IsNumeric(ce.Value) = True Then ce.Value = ce.Value * 0.01 End If Next ce With ActiveSheet.PivotTables("PivotTable1").PivotFields("Sum of Quantification") .NumberFormat = "0.0%" End With End Sub 

出现的错误是在ce.Value = ce.Value * .01那里我想乘以.01的单元格值,然后再将其转换为百分号格式。 我读这篇文章说,我必须创build一个计算值,但文章不是VBA相关的,我不知道如何在macros中创build一个计算值。

有更好的解决scheme吗?

而不是试图改变单元格的值,也许只是调整.NumberFormat ,如:

 ce.NumberFormat = "General\%" 

这样,你不需要做乘法运算。 这是一种自定义的数字格式,将会像1%一样呈现1而不会影响底层数据。