如何制作动态透视宏?

时间:2016-09-21 11:37:35

标签: vba excel-vba macros excel

我录制了一个用于插入数据透视的宏。由于宏被记录,它可以与特定的Excel工作表一起使用。但我想概括它,使其适用于所有工作表而不管行数。所以我想选择从'N6'开始到最后一个填充单元格的'N'列。这个我用过,  Range(Range("N5"), Range("N5").End(xlDown)).Select

但我想要一个动态的枢轴目的地。它应该是工作表中最后填充行下面的几行。我怎么做?

Sub Macro2()

Range("N6:N31").Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
    "Sheet1!R6C14:R31C14", Version:=xlPivotTableVersion14).CreatePivotTable _
    TableDestination:="Sheet1!R38C11", TableName:="PivotTable1", _
    DefaultVersion:=xlPivotTableVersion14
Sheets("Sheet1").Select
Cells(38, 11).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("BREAK TYPE")
    .Orientation = xlRowField
    .Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
    "PivotTable1").PivotFields("BREAK TYPE"), "Count of BREAK TYPE", xlCount

Range("K38").Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("BREAK TYPE")
    .Orientation = xlRowField
    .Position = 1
End With
ActiveWorkbook.ShowPivotTableFieldList = False

End Sub

1 个答案:

答案 0 :(得分:0)

下面的代码检查列N中数据的最后一行,然后检查“Sheet1”中是否已存在数据透视表。

如果有,它只是根据更新的数据刷新Pivot缓存。 如果没有,它会创建一个数据透视表(2行 - 不推荐)。

Option Explicit

Sub Macro2()

Dim shtPivot                        As Worksheet
Dim PivotSrc_Range                  As Range
Dim PvtTbl                          As PivotTable
Dim PvtCache                        As PivotCache
Dim lastRow                         As Long

' modify to your Sheet name that holds the Pivot source data
Set shtPivot = ThisWorkbook.Sheets("Sheet1")

With shtPivot
    lastRow = .Cells(.Rows.Count, "N").End(xlUp).Row

    ' setting dynamic Range in Column N
    Set PivotSrc_Range = Range("N6:N" & lastRow)

    ' for debug
    Debug.Print PivotSrc_Range.Address
End With

' set the Pivot Cache
Set PvtCache = ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PivotSrc_Range, Version:=xlPivotTableVersion14)

' add this line in case the Pivot table doesn't exit >> first time running this Macro
On Error Resume Next
Set PvtTbl = shtPivot.PivotTables("PivotTable1")

On Error GoTo 0
If PvtTbl Is Nothing Then

    ' create a new Pivot Table in "Sheet1" sheet, start 3 rows below your last line with data
    Set PvtTbl = shtPivot.PivotTables.Add(PivotCache:=PvtCache, TableDestination:=shtPivot.Range("N" & lastRow + 3), TableName:="PivotTable1")

    ' modify the name in brackets according to your Pivot Fields
    With PvtTbl.PivotFields("BREAK TYPE")
        .Orientation = xlRowField
        .Position = 1
    End With

    PvtTbl.AddDataField PvtTbl.PivotFields("BREAK TYPE"), "Count of BREAK TYPE", xlCount

Else
    ' just refresh the Pivot cache with the updated Range (data in Sheet1)
    PvtTbl.ChangePivotCache PvtCache
    PvtTbl.RefreshTable
End If

ActiveWorkbook.ShowPivotTableFieldList = False

End Sub