Excel VBA - 概括数据源数据/范围

时间:2013-06-10 23:30:48

标签: excel vba pivot-table

我录制了数据透视表宏,我正在尝试推广源数据,而不是取消工作表名称“REPORTS”

它抓取活动工作表中的所有数据,不管工作表的名称是什么。

这样我可以使用宏为任何活动工作表创建数据透视表: -

Sheets("**REPORTS**").Select
Range("A1").Select
Sheets.Add.Name = "Pivot"
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
    Sheets("**REPORTS**").Range("A1").CurrentRegion, Version:=xlPivotTableVersion15).CreatePivotTable _
    TableDestination:="Pivot!R3C1", TableName:="PivotTable1", DefaultVersion _
    :=xlPivotTableVersion15
Sheets("Pivot").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1")
    .InGridDropZones = True
    .RowAxisLayout xlTabularRow
End With

2 个答案:

答案 0 :(得分:1)

Sub TT()

    Dim shtSrc As Worksheet, shtDest As Worksheet
    Dim pc As PivotCache

    Set shtSrc = ActiveSheet

    Set shtDest = shtSrc.Parent.Sheets.Add()
    shtDest.Name = shtSrc.Name & "-Pivot"

    Set pc = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
        SourceData:=shtSrc.Range("A1").CurrentRegion)
    pc.CreatePivotTable TableDestination:=shtDest.Range("A3"), _
        TableName:="PivotTable1"

    With shtDest.PivotTables("PivotTable1")
        .InGridDropZones = True
        .RowAxisLayout xlTabularRow
    End With

End Sub

答案 1 :(得分:0)

这不会向数据透视表添加任何数据,但会创建它

Sub Example()
    Dim PrevSheet As Worksheet
    Set PrevSheet = ActiveSheet
    Range("A1").Select
    Sheets.Add.Name = "Pivot"
    PrevSheet.Select
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
                                      SourceData:=ActiveSheet.UsedRange, _
                                      Version:=xlPivotTableVersion15).CreatePivotTable _
                                      TableDestination:="Pivot!R3C1", _
                                      TableName:="PivotTable1", _
                                      DefaultVersion:=xlPivotTableVersion15
    Sheets("Pivot").Select
    Cells(3, 1).Select
    With ActiveSheet.PivotTables("PivotTable1")
        .InGridDropZones = True
        .RowAxisLayout xlTabularRow
    End With
End Sub