从VBAmacros的数据透视表显示不正确的数据

不知何故,我的数据透视表创build从我的VBA脚本显示不同的数据,当我手动创build数据透视表。

我的macros执行以下操作:

  • 数据库在工作表2中。枢轴位于工作表1中。
  • macros删除表2中的所有行并添加新数据。
  • M删除包含当前数据透视表的行。
  • M删除主键的数据连接。
  • M为表2中的新数据创build新的数据连接,并在表1中创build新的数据连接。

一切工作没有错误,但不知何故数据是不一样的,当我手动创build枢轴。

我的猜测是,它使用了一些旧的数据连接,但我不知道如何或如何解决这个问题。

VBA – 创build数据透视表的代码:

'Delete old pivot Sheets("Sheet1").Select Range("A1:C5").Select Selection.ClearContents 'Create new Connection ActiveWorkbook.Connections("PivotConnection").Delete Workbooks("File.xlsm").Connections.Add2 _ "PivotConnection", "", _ "WORKSHEET;*ABSOLUTE PATH*[File.xlsm]Sheet2" _ , "Sheet2!$A:$Q", 7, True, False 'Create new pivot ActiveWorkbook.PivotCaches.Create(SourceType:=xlExternal, SourceData:= _ ActiveWorkbook.Connections("PivotConnection"), Version:=6).CreatePivotTable _ TableDestination:=Worksheets("Sheet1").Cells(1, 1), TableName:="PivotTable3", DefaultVersion:=6 With ActiveSheet.PivotTables("PivotTable3") .ColumnGrand = True .HasAutoFormat = True .DisplayErrorString = False .DisplayNullString = True .EnableDrilldown = True .ErrorString = "" .MergeLabels = False .NullString = "" .PageFieldOrder = 2 .PageFieldWrapCount = 0 .PreserveFormatting = True .RowGrand = True .PrintTitles = False .RepeatItemsOnEachPrintedPage = True .TotalsAnnotation = True .CompactRowIndent = 1 .VisualTotals = False .InGridDropZones = False .DisplayFieldCaptions = True .DisplayMemberPropertyTooltips = True .DisplayContextTooltips = True .ShowDrillIndicators = True .PrintDrillIndicators = False .DisplayEmptyRow = False .DisplayEmptyColumn = False .AllowMultipleFilters = False .SortUsingCustomLists = True .DisplayImmediateItems = True .ViewCalculatedMembers = True .FieldListSortAscending = False .ShowValuesRow = False .CalculatedMembersInFilters = True .RowAxisLayout xlCompactRow End With ActiveSheet.PivotTables("PivotTable3").PivotCache.RefreshOnFileOpen = False ActiveSheet.PivotTables("PivotTable3").RepeatAllLabels xlRepeatLabels 

提前致谢

编辑:

只是为了澄清数据是不正确的:

  • 一行的不同数量给我例如1000
  • 我运行macros,并创build了修改后的数据的新主键
  • 不同的计数仍然显示1000
  • 手动创build的数据透视图显示了不同的数量,例如980