Search code examples
c#excelexcel-dna

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?


Solution

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