我有一个由400行和35列组成的表,并制作了一个VBA脚本来制作一个数据透视表,成功地比较了2列和12个单独的列。
在生成数据透视表时,会使用列标题(以避免混淆)。我是VBA的新手,这就是我把所有内容都归咎于我的错误
ActiveCell.Select
Range("AA3").Select
Selection.CurrentRegion.Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"Practitioners!R3C1:R246C27", Version:=xlPivotTableVersion15). _
CreatePivotTable TableDestination:="Practitioners!R3C29", TableName:= _
"PivotTable8", DefaultVersion:=xlPivotTableVersion15
Sheets("Practitioners").Select
Cells(3, 29).Select
ActiveWorkbook.ShowPivotTableFieldList = False
With ActiveSheet.PivotTables("PivotTable8").PivotFields("Capability")
.Orientation = xlRowField
.Position = 1
End With
With ActiveSheet.PivotTables("PivotTable8").PivotFields("Sub-Capability")
.Orientation = xlRowField
.Position = 2
End With
ActiveSheet.PivotTables("PivotTable8").AddDataField ActiveSheet.PivotTables( _
"PivotTable8").PivotFields("Grade"), "Count of Grade", xlCount
ActiveSheet.PivotTables("PivotTable8").AddDataField ActiveSheet.PivotTables( _
"PivotTable8").PivotFields("06-Feb-2017"), "Count of 06-Feb-2017", xlCount
但我的列标题每周都会更改,并且更改标题的名称意味着VBA代码将无效,因为它不再是" 06-Feb-2017"。
我尝试在代码中引用绝对单元格,但是出现了错误
运行时错误' 1004,无法获取的PivotFields属性 数据透视表类
有没有办法将PivotFields
称为绝对单元格引用(即B3)?
答案 0 :(得分:3)
尝试下面的代码(解释在代码注释中)。
您需要确保Cell“B3”的格式与PivotTable
中的格式相同,否则您将在以下行获得运行时错误:
.AddDataField PvtTbl.PivotFields(PvtFlfVal), "Count of " & PvtFlfVal, xlCount
<强>代码强>
Option Explicit
Sub DynamicPivotTableCountField()
Dim PvtTbl As Pivottable
Dim PvtFlfVal ' As String
' set the Pivot Table, replace "Sheet1" with your sheet's name (don't use ActiveSheet)
Set PvtTbl = Worksheets("Practitioners").PivotTables("PivotTable8")
' get the value from Cell B3, make sure it's formatted the way you need it for the Pivot Table later
PvtFlfVal = Format(Worksheets("Practitioners").Range("B3").Value, "dd-mmm-yyyy")
With PvtTbl
.AddDataField PvtTbl.PivotFields(PvtFlfVal), "Count of " & PvtFlfVal, xlCount
End With
End Sub