尝试使用另一个工作表中的数据范围的vba创建数据透视表时类型不匹配

时间:2014-08-04 20:49:28

标签: excel vba excel-vba

你好,当试图创建一个数据源被设置在不同工作表中的范围的数据透视表时,我经常会遇到类型不匹配或1004错误,这取决于我是如何声明我的源数据范围。以下是我的代码是否有人对如何正确设置我的范围有任何想法,以便此方法可以工作或我应该使用不同的方法来创建表?

Worksheets.Add.Name = sheetName

rowCount = CStr(Sheets(sourceName).UsedRange.Rows.Count)

Set rng = ThisWorkbook.Worksheets(sourceName).Range("A1:W" & rowCount)



'Create the Pivot Cache and Table

Set objCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, SourceData:=rng)

Set objTable = objCache.CreatePivotTable(TableDestination:=ActiveWorkbook.Worksheets(sourceName).Range("A1"))

1 个答案:

答案 0 :(得分:0)

尝试将整个范围放在一个字符串中:

Worksheets.Add.Name = sheetName

rowCount = Cstr(Sheets(sourceName).UsedRange.Rows.Count)

rowCount = "A1:W" & rowCount

Set rng = ThisWorkbook.Worksheets(sourceName).Range(rowCount)



'Create the Pivot Cache and Table

Set objCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, SourceData:=rng)

Set objTable = objCache.CreatePivotTable(TableDestination:=ActiveWorkbook.Worksheets(sourceName).Range("A1"))