【发布时间】:2020-01-31 10:47:33
【问题描述】:
我已经对如何将数据透视表添加到另一个工作簿进行了大量研究,但还不够。
我的数据集
宏存储在ThisWorkbook
数据透视表的源数据存储在打开工作簿 - 工作表名称“原始数据”
希望在同一打开工作簿上但在工作表名称“索赔摘要”上的数据透视表目标
警告
这个procedure 是一个更广泛的项目的一部分。因此我有几个module declarations:
Private wbReconcile As Workbook
Private wsRawData As Worksheet
Private wsSummary As Worksheet
然后将它们设置在不同的过程中(在同一模块内),如下所示:
Set wbReconcile = Workbooks.Open(RECON_FILE, False)
Set wsRawData = wbReconcile.Sheets("Raw Data")
Set wsSummary = wbReconcile.Sheets("Claim Summary")
问题与错误
我遇到的问题是,无论我使用variables 还是输入工作簿名称、工作表名称等。我总是在Set myPivotTable 行出现错误错误消息:运行时错误“5”:无效的过程调用或参数。
我的代码
Sub CreatePivotTable()
Dim myDestinationWorkbook As Workbook
Set myDestinationWorkbook = Workbooks("Template_Promo Claims Reconciliation.xlsm")
' Set myDestinationWorkbook = wbReconcile
Dim mySourceWorksheet As Worksheet
Set mySourceWorksheet = myDestinationWorkbook.Worksheets("Raw Data")
' Set mySourceWorksheet = wsRawData
Dim myDestinationWorksheet As Worksheet
Set myDestinationWorksheet = myDestinationWorkbook.Worksheets("Claim Summary")
' Set myDestinationWorksheet = wsSummary
'obtain address of destination cell range
Dim myDestinationRange As String
myDestinationRange = myDestinationWorksheet.Range("A1").Address(ReferenceStyle:=xlR1C1)
Dim mySourceData As String
mySourceData = mySourceWorksheet.Range("A1").CurrentRegion.Address(ReferenceStyle:=xlR1C1)
'create Pivot Table cache and create Pivot Table report based on that cache
Dim myPivotCache As PivotCache
Set myPivotCache = _
myDestinationWorkbook.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:="[" & myDestinationWorkbook.name & "]" & _
mySourceWorksheet.name & "!" & _
mySourceData)
Dim myPivotTable As PivotTable
Set myPivotTable = myPivotCache.CreatePivotTable(TableDestination:="[" & _
myDestinationWorkbook.name & "]" & myDestinationWorksheet.name & "!" & _
myDestinationRange, TableName:="RawDataPivot")
End Sub
编辑以显示如何使用答案
Sub AnswerPT()
Dim pc As PivotCache, pt As PivotTable
Dim wsSrc As Worksheet, wsDest As Worksheet
Dim rngSrc As Range, rngDest As Range
Set wsSrc = wsRawData
Set wsDest = wsSummary 'for convenience here
Set rngSrc = wsSrc.Range("A1").CurrentRegion 'source data
Set rngDest = wsDest.Range("A1") 'table location
Set pc = wsDest.Parent.PivotCaches.Create(SourceType:=xlDatabase, _
SourceData:=rngSrc, Version:=6)
Set pt = pc.CreatePivotTable(TableDestination:=rngDest, _
TableName:="PivotTable2", DefaultVersion:=6)
End Sub
【问题讨论】:
-
错误信息是什么?
-
更新帖子:错误消息:运行时错误“5”:无效的过程调用或参数。
-
如果
myDestinationWorksheet.Name包含空格,则工作表名称需要用单引号括起来。在这种情况下总是添加单引号并没有什么坏处。 -
@TimWilliams 怎么样?我迷路了,因为我尝试过双引号和各种......你能提供一个例子吗?
-
你试过只用
TableDestination := myDestinationWorksheet.Range("A1")吗?
标签: excel vba pivot-table