【发布时间】:2020-10-26 00:24:44
【问题描述】:
我正在尝试在 C# 中重新创建 VBA 代码以生成数据透视表
VBA 代码是
Sheets.Add
ActiveWorkbook.PivotCaches.Create(SourceType:= xlDatabase, SourceData:= _
"Sheet1!R1C1:R6C4", Version:= 6).CreatePivotTable TableDestination:= _
"Sheet2!R3C1", TableName:= "PivotTable1", DefaultVersion:= 6
Sheets("Sheet2").Select
Cells(3, 1).Select
With ActiveSheet.PivotTables("PivotTable1").PivotFields("First Name")
.Orientation = xlRowField
.Position = 1
End With
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables(_
"PivotTable1").PivotFields("Salary"), "Sum of Salary", xlSum
using Excel = Microsoft.Office.Interop.Excel;
...
//Start of pivot code
workbook.Worksheets.Add();
//ideally would want a "used range" here not specific cell addresses Sheet1!R1C1:R6C4
pivotcache = (Excel.PivotCache)excel.ActiveWorkbook.PivotCaches().Create(Excel.XlPivotTableSourceType.xlDatabase, "Sheet1!R1C1:R6C4", 6); // Const xlDatabase = 1 Member of Excel.XlPivotTableSourceType
pivot = pivotcache.CreatePivotTable("Sheet2!R3C1", "PivotTable1", 6);
sheet = (Excel.Worksheet) workbook.Worksheets["Sheet2"];
range = sheet.get_Range("A3");
range.Select();
pf = pivot.PivotFields("First Name");
pf.Orientation=XlPivotFieldOrientation.xlRowField; //1=xlrowfield
pf.Position = 1;
//*****Code fails here ***
df = pivot.AddDataField(pivot.PivotFields("Salary"), "Sum of Salary", XlConsolidationFunction.xlSum); //Const xlSum = -4157 (&HFFFFEFC3) Member of Excel.XlConsolidationFunction
最后一行失败并显示控制台错误消息:错误:此平台不支持操作。行:System.Private.CoreLib
谁能指点一下?
【问题讨论】:
标签: excel-interop