我编写了以下代码来从变量数据集创建数据透视表,以显示有多少学生在某个年级内获得了哪个分数范围。但是,它会返回运行时错误 5 消息,其中第 8-11 行由调试器突出显示。但我无法弄清楚出了什么问题
抱歉,如果这是基础知识,我是 VBA 新手!
(我注释了第 15 行,因为特定的数据透视表不需要任何列字段)
Sub create_pivot()
Dim mysourcedata, mydestination As String
Dim lr As Long
lr = Sheets("PPM").Range("A1").End(xlDown).Row
mysourcedata = "PPM!R1C1:R" & lr & "C" & Sheets("PPM").Cells(1, Columns.Count).End(xlToLeft).Column
mydestination = "Pivots and Graphs!R13C2"
Sheets("Pivots and Graphs").Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:=mysourcedata, Version:=8).CreatePivotTable _
TableDestination:=mydestination, TableName:="PivotTable5", _
DefaultVersion:=8
With ActiveSheet.PivotTables("PivotTable5")
.PivotFields("Grade").Orientation = xlPageField
.PivotFields("Range").Orientation = xlRowField
'.PivotFields("ColumnField").Orientation = xlColumnField
.PivotFields("Student Number").Orientation = xlDataField
End With
End Sub
我尝试过谷歌搜索,但找不到明确的答案,似乎有多种方法可以在 VBA 中编写命令来达到相同的结果!
如评论中所述,您可以使用
Range
对象,而无需创建它们的字符串表示形式:
例如:
Sub create_pivot()
Dim mysourcedata As Range, mydestination As Range
Dim lr As Long, lc As Long, wb As Workbook
Dim pc As PivotCache, pt As PivotTable
Set wb = ThisWorkbook 'or activeworkbook for example
With wb.Sheets("PPM")
lr = .Cells(.Rows.Count, "A").End(xlUp).Row
lc = .Cells(1, .Columns.Count).End(xlToLeft).Column
Set mysourcedata = .Range("A1", .Cells(lr, lc))
End With
Set mydestination = wb.Worksheets("Pivots and Graphs").Range("B13")
Set pc = wb.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:=mysourcedata, Version:=8)
Set pt = pc.CreatePivotTable(TableDestination:=mydestination, _
TableName:="PivotTable5", DefaultVersion:=8)
With pt
.PivotFields("Grade").Orientation = xlPageField
.PivotFields("Range").Orientation = xlRowField
'.PivotFields("ColumnField").Orientation = xlColumnField
.PivotFields("Student Number").Orientation = xlDataField
End With
End Sub