在数据透视数据源中使用变量

时间:2015-04-08 15:53:12

标签: vba

我想替换:

C:\Users\test_h\Downloads\New folder\[Book1.xlsm]Sheet1,其中包含以下代码中的变量:

ActiveSheet.PivotTables("PivotTable1").ChangePivotCache ActiveWorkbook. _

 PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _

 "C:\Users\test_h\Downloads\New folder\[Book1.xlsm]Sheet1!R1C1:R30C14", Version _
 :=xlPivotTableVersion14)

我已经尝试过,但无法让它发挥作用:

Sub test(sht As String, path_name As String)

   ActiveSheet.PivotTables("PivotTable1").ChangePivotCache ActiveWorkbook. _

   PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _

   path_name & sht & !R1C1:R30C14", Version _

   :=xlPivotTableVersion14)

End Sub

1 个答案:

答案 0 :(得分:0)

您遇到语法问题:缺少引号并在对象引用中打破行。在任何代码运行之前,编译器会捕获这些错误。另外,请使用Cells()引用代替R1C1地址引用。另外,您将字符串引用与工作簿和工作表组合在一起,并使用范围地址。

因此,请考虑使用声明的变量(并确保取消初始化):

Dim wkb As Workbook, wks As Worksheet
Dim SourceRng As Range
Dim NewCache As PivotCache

Set wkb = Workbooks.Open("C:\Users\test_h\Downloads\New folder\Book1.xlsm")
Set wks = wkb.Sheets("Sheet1")
Set SourceRng = wks.Range(Cells(1, 1), Cells(30, 14))
Set NewCache = ActiveWorkbook.PivotCaches.Create( _
                     SourceType:=xlDatabase, _
                     SourceData:=SourceRng, _
                     Version:=xlPivotTableVersion14)

ActiveSheet.PivotTables("PivotTable1").ChangePivotCache NewCache

Set wkb = Nothing
Set wks = Nothing
Set SourceRng = Nothing
Set NewCache = Nothing

通常为了便于阅读,有助于将参数分解为不同的行。当然这只是个人偏好。

相关问题