0

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

我正在使用的代码在我的 VBA 数据透视表宏中产生“运行时错误'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,然后再将它们转换为百分比数字格式。我读到这篇文章说我必须创建一个计算值,但这篇文章与 VBA 无关,我不知道如何在宏中创建计算值。

有更好的解决方案吗?

4

1 回答 1

3

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

ce.NumberFormat = "General\%"

这样,您不需要进行乘法运算。这是一种自定义数字格式,可以在不影响基础数据的情况下1呈现。1%

于 2013-07-29T18:10:29.337 回答