我在VBA中编写了这段代码,用于创建数据透视表(从宏转换它,实际上......),但它不起作用
Dim wsTarget As Worksheet
Dim rngSource As Range
Dim pc As PivotCache
Dim pt As PivotTable
Dim field As PivotField
Application.ScreenUpdating = False
Set rngSource = Summary.Range("A1").CurrentRegion
Set wsTarget = PivotTable
wsTarget.Select
For Each pt In wsTarget.PivotTables
pt.Delete
Next pt
Set pc = ThisWorkbook.PivotCaches.Create(xlDatabase, rngSource, xlPivotTableVersion15)
Set pt = pc.CreatePivotTable(wsTarget.Range("A3"), "PivotTable1", , xlPivotTableVersion15)
Set field = wsTarget.PivotTables("PivotTable1").PivotFields("A")
field.Orientation = xlColumnField
field.Position = 1
field.LayoutBlankLine = True
Set field = wsTarget.PivotTables("PivotTable1").PivotFields("B")
field.Orientation = xlRowField
field.Position = 1
Set field = wsTarget.PivotTables("PivotTable1").PivotFields("TOTAL")
Set field = wsTarget.PivotTables("PivotTable1").AddDataField(field, "Sum of TOTAL", xlSum)
field.NumberFormat = "_ $ * #,##0.00_ "
Application.ScreenUpdating = True
代码一直在“Set pc”行崩溃,我无法弄清楚为什么...... 尝试谷歌搜索,所有结果都与我的代码相同...... 重要细节 - 我正在使用excel 2013,也许是因为... 非常感谢我能得到的任何帮助 - 谢谢!
答案 0 :(得分:0)
试试这个..我认为你直接引用了工作表名称..
Set rngSource = Sheets("Summary").Range("A1").CurrentRegion
Set wsTarget = sheets("PivotTable")
答案 1 :(得分:0)
试试这个:
Dim lrow As Long
Dim lcol As Long
Dim rngSource As Range
lrow = ActiveSheet.Cells(Application.Rows.Count, 1).End(xlUp).Row
lcol = ActiveSheet.Cells(1, Application.Columns.Count).End(xlToLeft).Column
Set rngSource = ActiveSheet.Cells(1, 1).Resize(lrow, lcol)
答案 2 :(得分:0)