我正在尝试熟悉Excel-DNA,但无法找到有关如何在工作表单元格中循环选定值范围的文档。所以,我会有一个用户定义的函数,它将把一系列单元作为参数,我将获得一些数据。然后我会循环通过这个范围的单元格并对数据做一些事情。我该怎么做这种基本操作?我在Visual Studio中的代码看起来像这样。
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;
}
}
最简单的方法是让你的函数将参数声明为object[,]
类型。然后你将得到一个包含输入范围值的数组。您的代码可能如下所示:
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;
}
通常,您需要检查值对象的类型,并根据它执行不同的操作。从Excel-DNA传递的对象[,]数组可以包含以下类型的项目(取决于各个单元格中值的数据类型):
double
string
bool
ExcelDna.Integration.ExcelError
ExcelDna.Integration.ExcelEmpty
ExcelDna.Integration.ExcelMissing
(如果函数被调用,没有参数,如=Concat2()
)。