使用变量将数据添加到使用VBA的数据透视表的“值”字段中

时间:2017-03-29 07:11:45

标签: excel vba excel-vba pivot-table pivot-chart

我有一个看起来像这样的数据集 Dataset 然而,我的天数是一个变量,并将继续变化。

我想使用VBA创建数据透视表,代码如下:

Sheets("Initialize").Select
NoRes = Cells(6, 3).Value
Sheets("Metric Calculations").Select
ProjDur = Cells(31, 4).Value
Range(Cells(31, 61), Cells(30 + NoRes, 61 + ProjDur)).Select
Selection.Copy
Sheets("Resource Histogram Data").Select
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Range(Cells(1, 1), Cells(1 + NoRes, 1 + ProjDur)).Select
Application.CutCopyMode = False
r = 1 + NoRes
p = 1 + ProjDur
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=Sheets("Resource Histogram Data").Range(Cells(1, 1), Cells(r, p)), Version:=6). _
    CreatePivotTable TableDestination:="Sheet1!R1C1", TableName:="PivotTable1", DefaultVersion:=6
Sheets("Sheet1").Select
Cells(1, 1).Select
ActiveWorkbook.ShowPivotTableFieldList = True
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$1:$C$18")
With ActiveChart.PivotLayout.PivotTable.PivotFields("Resources")
    .Orientation = xlPageField
    .Position = 1
End With
    ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
        PivotTable.PivotFields("Day 1"), "Sum of Day 1", xlSum
    ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
        PivotTable.PivotFields("Day 2"), "Sum of Day 2", xlSum
    ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
        PivotTable.PivotFields("Day 3"), "Sum of Day 3", xlSum
ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
    PivotTable.PivotFields("Day 4"), "Sum of Day 4", xlSum
ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
    PivotTable.PivotFields("Day 5"), "Sum of Day 5", xlSum
ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
    PivotTable.PivotFields("Day 6"), "Sum of Day 6", xlSum
ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
    PivotTable.PivotFields("Day 7"), "Sum of Day 7", xlSum
ActiveChart.ShowValueFieldButtons = False

在AddDataField重复七次的代码的最后部分。当天数变化(在1到200之间)时,理想情况下应该是for循环。但是这样做显然不起作用。

For i = 1 To ProjDur    
    ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
    PivotTable.PivotFields("Day i"), "Sum of Day i", xlSum    
Next i

如何获得我的代码中包含的循环函数?

1 个答案:

答案 0 :(得分:0)

这将是:

For i = 1 To ProjDur    
    ActiveChart.PivotLayout.PivotTable.AddDataField ActiveChart.PivotLayout. _
    PivotTable.PivotFields("Day " & i), "Sum of Day " & i, xlSum
Next i