VBA 从变量数据集创建数据透视表

VBA to create a Pivot Table from a Variable Dataset

提问人:ConorWJ 提问时间:11/6/2023 最后编辑:braXConorWJ 更新时间:11/7/2023 访问量:43

问:

我编写了以下代码,从变量数据集创建一个数据透视表,以显示有多少学生在某个年级内获得了什么范围的分数。但是,它会返回运行时错误 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中编写命令以得出相同的结果!

Excel VBA 数据透视表

评论

0赞 Black cat 11/6/2023
SourceData 和 TableDestination 需要范围。在分配两个变量时使用,并使用 Range 语法。Set
1赞 Domenic 11/6/2023
由于您的工作表名称包含空格,因此请尝试将其换行在单引号中。mydestination = "'Pivots and Graphs'!R13C2"

答:

1赞 Tim Williams 11/7/2023 #1

如注释中所述,您可以使用对象,而无需创建它们的字符串表示形式: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