我想将一个范围(此时为 1d)传递给我的函数,并返回一个包含该范围公式的字符串数组。
到目前为止,这是我的(不工作)代码:
public static object[,] ReadFormulas([ExcelArgument(AllowReference=true)]object arg)
{
ExcelReference theRef = (ExcelReference)arg;
object[,] o = (object[,])theRef.GetValue();
string[,] res = new string[o.GetLength(1),1];
for(int i=0;i<o.GetLength(1);i++)
{
ExcelReference cellRef = new ExcelReference(theRef.RowFirst+i, theRef.ColumnFirst);
res[i,0] = XlCall.Excel(XlCall.xlfGetFormula, cellRef) as string; //Errors here
}
return res;
}
Run Code Online (Sandbox Code Playgroud)
GET.FORMULA (xlfGetFormula) 函数只允许在宏工作表上使用。要从工作表调用它,您的 Excel-DNA 函数应标记为IsMacroType=true,如下所示:
[ExcelFunction(IsMacroType=true)]
public static object[,] ReadFormulas(
[ExcelArgument(AllowReference=true)]object arg) {...}
Run Code Online (Sandbox Code Playgroud)
此外,在循环中构造新的 ExcelReference 时需要小心一点。默认情况下,引用中引用的工作表将是当前工作表,而不是传入引用的工作表。您可能应该明确地将 SheetId 传递到新的 ExcelReference 中。您的索引也有一些有趣的地方 - 也许这o.GetLength(1)不是您想要的。
以下版本似乎有效:
[ExcelFunction(IsMacroType=true)]
public static object[,] ReadFormulasMacroType(
[ExcelArgument(AllowReference=true)]object arg)
{
ExcelReference theRef = (ExcelReference)arg;
int rows = theRef.RowLast - theRef.RowFirst + 1;
object[,] res = new object[rows, 1];
for(int i=0; i < rows; i++)
{
ExcelReference cellRef = new ExcelReference(
theRef.RowFirst+i, theRef.RowFirst+i,
theRef.ColumnFirst,theRef.ColumnFirst,
theRef.SheetId );
res[i,0] = XlCall.Excel(XlCall.xlfGetFormula, cellRef);
}
return res;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6443 次 |
| 最近记录: |