2012-11-06 54 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