[英]Excel-Dna C# How to get values from selected range in excel worksheet
我正在尝试熟悉 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 传递的 object[,] 数组可以包含以下类型的项目(取决于相应单元格中值的数据类型):
double
string
bool
ExcelDna.Integration.ExcelError
ExcelDna.Integration.ExcelEmpty
ExcelDna.Integration.ExcelMissing
(如果不带参数调用该函数,则为=Concat2()
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.