0

我正在尝试编写一个用于创建数据透视图的宏。在 DI 列的工作表中有用户列表。一个用户名可以是 D 列中的次数。我试图从总用户数中找出每个用户名的百分比

我需要绘制一个柱形图,X 轴为用户,Y 轴为 %。该图表应在 D 列中最后一个单元格的 3 行之后开始。D 列中的行数每次都会根据采样率而变化。我正在尝试这样做来自动化一些测试结果。

我试过的代码

lastTC = Range("D" & Rows.Count).End(xlUp).Row
lastTCP = lastTC + 3
lastTCP1 = lastTC + 10
lastTCC = lastTC + 18

lastTC = Range("D" & Rows.Count).End(xlUp).Row
Range("D1", "D" & lastTC).Select
 ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
    ("TOPMEM!$D$1:$D" & lastTC), Version:=xlPivotTableVersion14).CreatePivotTable _
    TableDestination:=("TOPMEM!R1C10"), TableName:="PivotTable5", _
    DefaultVersion:=xlPivotTableVersion14

Sheets("TOPMEM").Select
Cells(724, 1).Select
ActiveWorkbook.ShowPivotTableFieldList = True
With ActiveSheet.PivotTables("PivotTable5").PivotFields("USER")
    .Orientation = xlRowField
    .Position = 1
End With
ActiveSheet.PivotTables("PivotTable5").AddDataField ActiveSheet.PivotTables( _
    "PivotTable5").PivotFields("USER"), "Count of USER", xlCount

Range("K1").Select
With ActiveSheet.PivotTables("PivotTable9").PivotFields("Count of USER")
    .Calculation = xlPercentOfTotal
    .NumberFormat = "0.00%"
End With
ActiveWorkbook.ShowPivotTableFieldList = False
4

1 回答 1

0

Your pivot table name must be incorrect. Right click on your pivot table and select Pivot Table Options from the context menu. Check the pivot table name at the top of the popup window.

In addition, use code like this:

Sub test()
    Dim p As PivotTable
    Dim s As Worksheet
    Set s = ThisWorkbook.Sheets("Sheet4")
    Set p = s.PivotTables("PivotTable1")
End Sub

It is more robust and easier to debug. If you click on a different sheet while the macro is running, it will fail. With the above code, this would not happen. Avoid ActiveSheet and ActiveWorkbook in general.

于 2013-09-11T12:31:35.647 回答