简体   繁体   English

Excel VBA数据透视图

[英]Excel VBA Pivot chart

I am trying to write a macro for creating a pivot chart. 我正在尝试编写一个用于创建数据透视图的宏。 In a sheet in column DI have the list of users. 在DI栏中的工作表中有用户列表。 One username can be number of time in column D. I'm trying to find out % of each username from the overall usercount 一个用户名可以是D列中的时间。我正在尝试从总用户数中找出每个用户名的百分比

I need to draw a column chart, user in X axis and % in Y axis. 我需要绘制一个柱形图,用户在X轴上,%在Y轴上。 The chart should start after 3 rows of the last cell in column D. The number of rows in column D will vary every time depending on the sample rate. 该图表应在D列中最后一个单元格的3行之后开始。D列中的行数每次都将根据采样率而变化。 I am trying this to automate some of the test results. 我正在尝试以此自动化一些测试结果。

The code I tried 我试过的代码

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

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. 通常避免使用ActiveSheet和ActiveWorkbook。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM