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;
}
}
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()
).
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.