Delphi 10/Seattle,带有 Excel 2013。我正在为 Excel 编写一个插件(使用 AddIn Express)。我需要做的一件事是创建一系列 Excel 数据透视表/数据透视图。我在 Excel 中记录了宏,所以我有 VBA 代码来做我想做的事。我的挑战是将它移植到德尔福。
我的代码编译了,当我单步执行时,最后一行给了我错误.. 自动化对象不支持方法“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 对象吗?现在,它被硬编码到特定的单元格位置,但根据数据,我的数据透视表可能比从第 3 行到第 20 行更大。
如果有帮助,VBA 宏代码(最后 2 行)是..
ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
ActiveChart.SetSourceData Source:=Range("Sheet1!$A$3:$C$20")
最佳答案
我找到了答案。代替
// Tell the Pivot Chart to use the Chart Range
myChart.SetSourceData(ChartSourceRange)
代码应该是
myChart.chart.SetSourceData(ChartSourceRange);
关于excel - Delphi 控制 Excel - 创建数据透视表和图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40536189/