如何使用Excel-DNA迭代行?

时间:2016-05-09 14:31:08

标签: c# excel excel-dna

我正在寻找一个excel-dna迭代工作表中的单元格的简单示例。我想我会有这样的事情:

public static class Test {

    [ExcelCommand(MenuName = "Range Tools", MenuText = "Iterator")]
    public static void IterateOverRows(string worksheetName, string startAddress, string endAddress) {
    ...
    }
}

我将使用将运行的按钮点击从Excel调用此加载项:

   Application.Run("IterateOverRows", "Sheet1", "A1", "C3")

有关如何在Excel-DNA中执行此操作的任何指示?

1 个答案:

答案 0 :(得分:1)

这有效:

using Excel = Microsoft.Office.Interop.Excel;

[ExcelCommand]
public static void IterateOverRows(string worksheetName, string startAddress, string endAddress) {
    var app = (Excel.Application)ExcelDnaUtil.Application;
    var ws = (Excel.Worksheet)app.ActiveWorkbook.Sheets[worksheetName];
    var rows = ws.Range[$"{startAddress}:{endAddress}"].Rows.OfType<Excel.Range>();
    foreach (var row in rows) {
        row.Cells[1, 1].Value = "aaaa";
    }
}

或者您可以使用此功能并将其称为Application.Run "IterateOverRows2", [Sheet1!B2:C10]

[ExcelCommand]
public static void IterateOverRows2([ExcelArgument(AllowReference = true)] object range) {
    var app = (Excel.Application)ExcelDnaUtil.Application;
    var xlRng = app.Range[XlCall.Excel(XlCall.xlfReftext, (ExcelReference)range, true)];
    var rows = xlRng.Rows.OfType<Excel.Range>();
    foreach (var row in rows) {
        row.Cells[1, 1].Value = "aaaa";
    }
}