Excel-Dna C# How to get values from selected range in excel worksheet
Asked Answered
S

1

6

I am trying to get familiar with Excel-DNA but cannot find documentation on how I could loop through a selected range of values in worksheet cells. So, I would have a user defined function which would take as parameters a range of cells where I would have some data. Then I would loop trough this range of cells and do something with the data. How can I do this kind of basic operation? My code in Visual Studio could look something like this.

using System;
using System.Collections.Generic;
using ExcelDna.Integration;

namespace myUDF
{
    public static class Class1
    {
        [ExcelFunction(Name = "LoopArrayTester")]
        public static List<double> LoopArrayTester(??? range)
        {
            List<double> list = new List<double>();

            // loop through somehow the range in worksheet given
            // somehow in the method signature

            for(int i = 0; i < range.count; i++)
            {
                // get values of i'th cell in range and put it to list
                // or something.
            }
        }

        return list;
    }
}
Snowinsummer answered 30/8, 2018 at 12:6 Comment(0)
K
5

Easiest is to let your function declare the parameter as type object[,]. Then you'll get an array with the values from the input range. Your code might look like this:

public static object Concat2(object[,] values)
{
    string result = "";
    int rows = values.GetLength(0);
    int cols = values.GetLength(1);
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            object value = values[i, j];
            result += value.ToString();
        }
    }
    return result;
}

Typically you'd want to check the type of the value object, and do something different based on that. The object[,] array passed from Excel-DNA could have items of the following types (depending on the data type of the values in the respective cells):

  • double
  • string
  • bool
  • ExcelDna.Integration.ExcelError
  • ExcelDna.Integration.ExcelEmpty
  • ExcelDna.Integration.ExcelMissing (if the function is called with no parameter, as =Concat2()).
Kopeisk answered 30/8, 2018 at 13:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.