【问题标题】:AddDataField function fails with Microsoft.Office.Interop.ExcelAddDataField 函数因 Microsoft.Office.Interop.Excel 而失败
【发布时间】: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


    【解决方案1】:

    像这样分解代码并添加方向 xlDataField

    df = pivot.PivotFields("Salary");
    df.Orientation = XlPivotFieldOrientation.xlDataField;
    df.Function = Excel.XlConsolidationFunction.xlSum; 
    df.Caption = "Sum of Salary";
    

    【讨论】:

      猜你喜欢
      • 2015-06-20
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 1970-01-01
      • 2018-02-16
      • 2018-10-18
      • 2022-11-22
      • 1970-01-01
      相关资源
      最近更新 更多