2012-11-06 79 views
5

我想弄清楚如何使用VBA更改數據更改我的數據透視表源數據到行的末尾。我當前的代碼如下:VBA更新數據透視表的源數據到行尾

Dim shBrandPivot As Worksheet 
Dim shCurrentWeek As Worksheet 
Dim shPriorWeek As Worksheet 
Dim shPivot As Worksheet 
Dim lr As Long 


Set shBrandPivot = ActiveWorkbook.Sheets("Brand Pivot") 
Set shCurrentWeek = ActiveWorkbook.Sheets("Current Week") 
Set shPriorWeek = ActiveWorkbook.Sheets("Prior Week") 
Set shPivot = ActiveWorkbook.Sheets("Pivot") 
lr = shCurrentWeek.Range("A" & Rows.Count).End(xlUp).Row 

With ActiveWorkbook.Sheets("Pivot").Activate 

ActiveSheet.PivotTableWizard SourceType:=xlDatabase, SourceData:="CurrentWeek!A3:X & lr" 

End With 

我正的錯誤是運行時錯誤1004:無法打開數據透視表源文件:E:\脫機\ KXM2103 \ DATA \ CurrentWeek

+0

是否可以使用動態定義的範圍,然後在代碼中簡單地刷新數據透視表?你的數據如何更新? – scott

+0

@scott現在,我的數據正在手動更新,轉到選項 - >更改源數據。我正在考慮嘗試你所討論的方法,但我想看看是否有辦法通過VBA專門做到這一點。 – kmiao91

回答

5

要完全做到這一點的VBA你可以試試這個。

Dim shBrandPivot As Worksheet 
Dim shCurrentWeek As Worksheet 
Dim shPriorWeek As Worksheet 
Dim shPivot As Worksheet 
Dim lr As Long 
dim rng as range 

Set shBrandPivot = ActiveWorkbook.Sheets("Brand Pivot") 
Set shCurrentWeek = ActiveWorkbook.Sheets("Current Week") 
Set shPriorWeek = ActiveWorkbook.Sheets("Prior Week") 
Set shPivot = ActiveWorkbook.Sheets("Pivot") 
lr = shCurrentWeek.Range("A" & Rows.Count).End(xlUp).Row 
set rng = shcurrentweek.range("A3:X" & lr) 

With shPivot.PivotTables(1).PivotCache 
     .SourceData = rng.Address(True, True, xlR1C1, True) 
     .Refresh 
End With 
+0

我在xlPivotTableVersion14(變量沒有定義)編輯錯誤 – kmiao91

+0

編輯它只是刪除版本並堅持使用默認 – scott

+0

我現在收到一個「對象需要」的錯誤代碼 – kmiao91