简体   繁体   中英

How do I use Excel-DNA to iterate over rows?

I am looking for a simple example of excel-dna iterating over cells in a worksheet. I would imagine I would have something like this:

public static class Test {

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

I would Invoke this add-In from Excel using a button click that will run:

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

Any pointers on how to do this in Excel-DNA?

This works:

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";
    }
}

Or you could use this and call it like 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";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM