为什么录制的Pivot创buildmacros(VBA)中存在无效的引用?

我用macroslogging器创build了这个代码来自动获取数据透视表。

但是当我再次运行这个代码时会出现一个错误信息:

运行时错误1004:无效的引用

在这行Workbooks("works.xlsm").Connections.Add2

为什么这个代码被logging的时候会有无效的引用? 在录音过程中,我为表格命名了“数据库”(R1C4:R18532C9)。 我使用Windows 10和Office 2016。

 Range("D1").Select Range(Selection, Selection.End(xlToRight)).Select Range(Selection, Selection.End(xlDown)).Select ActiveWorkbook.Names.Add Name:="database", RefersToR1C1:= _ "=Data!R1C4:R18532C9" ActiveWorkbook.Names("database").Comment = "" Range("D1").Select Workbooks("works.xlsm").Connections.Add2 _ "WorksheetConnection_works.xlsm!database", "", _ "WORKSHEET;C:\Users\gabor\Documents\CAFM\VBS\works.xlsm", _ "works.xlsm!database", 7, True, False ActiveWorkbook.PivotCaches.Create(SourceType:=xlExternal, SourceData:= _ ActiveWorkbook.Connections("WorksheetConnection_works.xlsm!database"), _ Version:=6).CreatePivotTable TableDestination:="Pivot!R1C1", TableName:= _ "Statement1", DefaultVersion:=6 Sheets("Pivot").Select Cells(1, 1).Select With ActiveSheet.PivotTables("Statement1").CubeFields("[database].[Person]") .Orientation = xlRowField .Position = 1 End With 

数据库表和主键结果使用xlCount和xlDistinctCount

在这里输入图像说明

尝试编辑下面的代码,解释是在代码里面的注释。

xlDistinctCount是未经testing,因为我有Office 2010(它可从Officde 2013),但应该工作。

 Option Explicit Sub AutoDynamicPivot() Dim PT As PivotTable Dim PTCache As PivotCache Dim WB As Workbook Dim Sht As Worksheet Dim SrcData As Variant Dim lRow As Long, lCol As Long Set WB = ThisWorkbook Set Sht = WB.Worksheets("Data") '<-- set the "Data" worksheet lRow = Sht.Range("A1").End(xlDown).Row '<-- modifed from "D1" to "A1" (according to PO screen-shot) lCol = Sht.Range("A1").End(xlToRight).Column '<-- modifed from "D1" to "A1" (according to PO screen-shot) ' set the Named Range "database" to the data in worksheet "Data" WB.Names.Add Name:="database", RefersToR1C1:="=" & Sht.Name & "!R1C1:R" & lRow & "C" & lCol '<-- modifed to "R1C1" (according to PO screen-shot) WB.Names("database").Comment = "" ' Determine the data range you want for your Pivot Cache Set SrcData = Range("database") ' set the Pivot Cache Set PTCache = ActiveWorkbook.PivotCaches.Add(xlDatabase, SrcData) ' add this line in case the Pivot table doesn't exit >> first time running this Macro On Error Resume Next Set PT = Worksheets("Pivot").PivotTables("Statement1") ' check if "Statement1" Pivot Table already created (in past runs of this Macro) On Error GoTo 0 If PT Is Nothing Then ' create a new Pivot Table in "Pivot" sheet, start from Cell A1 Set PT = Worksheets("Pivot").PivotTables.Add(PivotCache:=PTCache, TableDestination:=Worksheets("Pivot").Range("A1"), TableName:="Statement1") 'Create the headings and row and column orientation and all of your other settings here With PT ' set "Person" as rows field With .PivotFields("Person") .Orientation = xlRowField .Position = 1 End With ' set "Month" as Filter With .PivotFields("Month") .Orientation = xlPageField .Position = 1 End With ' set "Count of Cases" .AddDataField .PivotFields("Case"), "Count of Case", xlCount ' set "Distinct Count of Cases" .AddDataField .PivotFields("Case"), "Distinct Count of Case", xlDistinctCount End With Else ' just refresh the Pivot cache with the updated Range (data in "Data" worksheet) PT.ChangePivotCache PTCache PT.RefreshTable End If End Sub 

用此代码创build的数据透视表的屏幕截图:

在这里输入图像说明

我将Connections.Add2中的commandtext参数从“works.xlsm!database”更改为“Data!database”。 它解决了这个问题。 我编辑了ActiveWorkbook.Names.Add以及。

 LastRow = Sheets("Data").Cells(Rows.Count, 1).End(xlUp).Row LastCol = Sheets("Data").Cells(1, Columns.Count).End(xlToLeft).Column ActiveWorkbook.Names.Add _ Name:="database", _ RefersTo:="=Data!R1C4:R" & LastRow & "C" & LastCol & "" ActiveWorkbook.Connections.Add2 _ "WorksheetConnection_works.xlsm!database", "", _ "WORKSHEET;C:\Users\gabor\Documents\CAFM\VBS\works.xlsm", _ "Data!database", 7, True, False ActiveWorkbook.PivotCaches.Create(SourceType:=xlExternal, SourceData:= _ ActiveWorkbook.Connections("WorksheetConnection_works.xlsm!database"), _ Version:=6).CreatePivotTable TableDestination:="Pivot!R1C1", TableName:= _ "Statement1", DefaultVersion:=6 Sheets("Pivot").Select Cells(1, 1).Select With ActiveSheet.PivotTables("Statement1").CubeFields("[database].[Person]") .Orientation = xlRowField .Position = 1 End With 

我可以用这个代码得到xlDistinctCount:

 ActiveSheet.PivotTables("Statement1").CubeFields.GetMeasure "[database].[TT]" _ , xlCount ActiveSheet.PivotTables("Statement1").AddDataField ActiveSheet.PivotTables( _ "Statement1").CubeFields("[Measures].[quantity of items - TT]") With ActiveSheet.PivotTables("Statement1").PivotFields( _ "[Measures].[quantity of items - TT]") .Caption = "number of distinct items – TT" .Function = xlDistinctCount End With 

我必须先使用xlCount,并以此结果我可以得到xlDistinctCount。