2016-12-28 69 views
0

我試圖將我的固定範圍(A1:G4193)更改爲動態,因爲需要每天輸入新數據。在數據透視表中創建動態範圍

這裏是我的代碼:

Sub Create_Pivot() 

Dim sht As Worksheet 
Dim pvtCache As PivotCache 
Dim pvt As PivotTable 
Dim StartPvt As String 
Dim SrcData As String 
Dim pf As PivotField 

SrcData = ActiveSheet.Name & "!" & Range("A1:G4193").Address(ReferenceStyle:=xlR1C1) 

Set sht = Sheets.Add 

StartPvt = sht.Name & "!" & sht.Range("A1").Address(ReferenceStyle:=xlR1C1) 

Set pvtCache = ActiveWorkbook.PivotCaches.Create(_ 
    SourceType:=xlDatabase, _ 
    SourceData:=SrcData) 

Set pvt = pvtCache.CreatePivotTable(_ 
    TableDestination:=StartPvt, _ 
    TableName:="PivotTable1") 

我非常感謝所有幫助。謝謝!

+0

列數是否改變,或者只是行數?看看[這個簡單的代碼](http://stackoverflow.com/questions/11169445/error-in-finding-last-used-cell-in-vba)來確定最後一行.. – OldUgly

回答

0

假設 - 您的數據透視表的動態範圍是通過添加(或分心)的行數發生變化,而列數保持不變。

而不是使用ActiveSheet,嘗試使用引用的對象,如Set SrcSht = Worksheets("Sheet1"),然後使用該變量。

嘗試下面的代碼(我的其他一些修改是在代碼的註釋內)。

Option Explicit 

Sub Create_Pivot_DynamicRange() 

Dim sht As Worksheet 
Dim pvtCache As PivotCache 
Dim pvt As PivotTable 
Dim StartPvt As Range 
Dim SrcData As String 
Dim pf As PivotField 

Dim SrcSht As Worksheet, LastRow As Long 

' modify "Sheet1" to your sheet's name 
Set SrcSht = Worksheets("Sheet1") 

With SrcSht 
    ' find last row with data in Column A (skip blank cells in the middle) 
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 
    ' set source data to dynamic number of rows (string) 
    SrcData = .Name & "!" & .Range("A1:G" & LastRow).Address(ReferenceStyle:=xlR1C1) 
End With 

Set sht = Sheets.Add 

' set the start position directly to a Range (there's no need to use a String as a "middle-man") 
Set StartPvt = sht.Range("A1") 

Set pvtCache = ActiveWorkbook.PivotCaches.Create(_ 
    SourceType:=xlDatabase, _ 
    SourceData:=SrcData) 

Set pvt = pvtCache.CreatePivotTable(_ 
    TableDestination:=StartPvt, _ 
    TableName:="PivotTable1") 

End Sub 
0

改變你的範圍到一個變量 - 如RNG 計算範圍,你打算怎麼做。最後一排,最後一列,最後一個單元格地址等 然後使代碼soething這樣

Lastrow = ActiveSheet..Range("B" & Worksheets("All_Data").Rows.Count).End(xlUp).Row 
    RNG = "A1:"G" & Lastrow 
    SrcData = ActiveSheet.Name & "!" & Range(RNG).Address(ReferenceStyle:=xlR1C1)