Delphi控制Excel – 创build数据透视表和图表

delphi10 /西雅图,与Excel 2013.我正在写一个插件(使用AddIn Express)的Excel。 我需要做的一件事是创build一系列Excel数据透视表/数据透视图。 我在Excel中logging了macros,所以我有VBA代码来做我想要的。 我的挑战是将其移植到Delphi。

我的代码编译,当我通过它时,最后一行给我的错误..自动化对象不支持方法'SetSourceData'。 仅供参考 – XLApp是Excel应用程序的可变点。

procedure TMyTemplateForm.Pivot_TouchesByQuarter; var myPivotCache: OleVariant; myActive_WB : OleVariant; MyChart : OleVariant; ChartSourceRange : OleVariant; TabDestination : string; begin // Add the new Sheet XLApp.Connect; myActive_WB := XLApp.ActiveWorkbook; XLApp.Worksheets.Add(EmptyParam, EmptyParam,1, xlWorksheet, LOCALE_USER_DEFAULT ); // Get a handle to the new sheet and set the Sheet Name sheet_graph1 := XLApp.ActiveSheet; sheet_graph1.Name := 'Graph1'; // CANNOT CONTAIN SPACES.. ????? // Parameters: SourceType, SourceData, Version // Doc at: https://msdn.microsoft.com/en-us/library/office/ff839430.aspx myPivotCache := myActive_WB.PivotCaches.Create(xlDatabase,'Raw Data!R1C1:R1048576C36',xlPivotTableVersion15); // Parameters: TableDestination, TableName, DefaultVersion TabDestination := 'Graph1!R3C1'; myPivotCache.CreatePivotTable(TabDestination, 'PivotTable1',xlPivotTableVersion15); // Select where we want this placed... sheet_Graph1.Cells.Item[3, 1].Select; // https://msdn.microsoft.com/en-us/library/office/jj228277.aspx // Create the chart object myChart := sheet_Graph1.Shapes.AddChart2(201, xlColumnClustered); // Define the Range that is the source for the chart. This is the Pivot Table I created just above ChartSourceRange := sheet_Graph1.Range['Graph1!$A$3:$C$20']; // Tell the Pivot Chart to use the Chart Range myChart.SetSourceData(ChartSourceRange); end; 

为什么我得到这个错误? 作为一个相关的问题,我可以将我的图表来源指向PivotTable1对象吗? 现在,它被硬编码到特定的单元格位置,但根据数据,我的数据透视表可能比从Row3到Row20更大。

如果有帮助,VBAmacros代码(最后2行)是..

  ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select ActiveChart.SetSourceData Source:=Range("Sheet1!$A$3:$C$20") 

我find了答案。 代替

  // Tell the Pivot Chart to use the Chart Range myChart.SetSourceData(ChartSourceRange) 

代码应该是

  myChart.chart.SetSourceData(ChartSourceRange);