从单元格函数中修改工作表值基本上是一个坏主意。执行单元格函数时,Excel 通常很忙。因此,修改某个单元格值的尝试可能会失败。
你的代码是正确的。你唯一缺少的是是宏类型=真的ExcelFunction 属性的属性。该属性改变了函数与工作表交互的方式。有关详细信息,请参阅here。代码示例如下。
[ExcelFunction(IsMacroType = true)]
public static int TestWrite1()
{
Excel.Range xlCell;
Excel.Application xlapp = (Excel.Application)ExcelDnaUtil.Application;
xlapp.Visible = true;
Worksheet currentSheet;
xlCell = xlapp.ActiveCell;
Excel.Workbook wbook = xlapp.ActiveWorkbook;
currentSheet = wbook.ActiveSheet;
currentSheet.Cells[1, 1].Value = "Hello, world";
return 0;
}
或者,您可以使用该函数手动将代码排队以执行ExcelAsyncUtil.QueueAsMacro. Excel 准备就绪后,它将安全地运行您的委托。有关该功能的更多详细信息,请参阅here。示例如下。
[ExcelFunction]
public static int TestWrite2()
{
ExcelAsyncUtil.QueueAsMacro(new ExcelAction(() => {
Excel.Range xlCell;
Excel.Application xlapp = (Excel.Application)ExcelDnaUtil.Application;
xlapp.Visible = true;
Worksheet currentSheet;
xlCell = xlapp.ActiveCell;
Excel.Workbook wbook = xlapp.ActiveWorkbook;
currentSheet = wbook.ActiveSheet;
currentSheet.Cells[1, 1].Value = "Hello, world";
}));
return 0;
}
最后,如果您的目标是从单元格函数返回一些值到活动单元格,您可以正常返回该值。
[ExcelFunction]
public static string TestWrite3()
{
Excel.Range xlCell;
Excel.Application xlapp = (Excel.Application)ExcelDnaUtil.Application;
xlapp.Visible = true;
Worksheet currentSheet;
xlCell = xlapp.ActiveCell;
Excel.Workbook wbook = xlapp.ActiveWorkbook;
currentSheet = wbook.ActiveSheet;
/* Insert to the current cell where the cell-function is being executed. */
return "Hello, world";
}
完整代码如下:
using ExcelDna.Integration;
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
namespace ClassLibraryExcelDna
{
public class UDF
{
[ExcelFunction(IsMacroType = true)]
public static int TestWrite1()
{
Excel.Range xlCell;
Excel.Application xlapp = (Excel.Application)ExcelDnaUtil.Application;
xlapp.Visible = true;
Worksheet currentSheet;
xlCell = xlapp.ActiveCell;
Excel.Workbook wbook = xlapp.ActiveWorkbook;
currentSheet = wbook.ActiveSheet;
currentSheet.Cells[1, 1].Value = "Hello, world";
return 0;
}
[ExcelFunction]
public static int TestWrite2()
{
ExcelAsyncUtil.QueueAsMacro(new ExcelAction(() => {
Excel.Range xlCell;
Excel.Application xlapp = (Excel.Application)ExcelDnaUtil.Application;
xlapp.Visible = true;
Worksheet currentSheet;
xlCell = xlapp.ActiveCell;
Excel.Workbook wbook = xlapp.ActiveWorkbook;
currentSheet = wbook.ActiveSheet;
currentSheet.Cells[1, 1].Value = "Hello, world";
}));
return 0;
}
[ExcelFunction]
public static string TestWrite3()
{
Excel.Range xlCell;
Excel.Application xlapp = (Excel.Application)ExcelDnaUtil.Application;
xlapp.Visible = true;
Worksheet currentSheet;
xlCell = xlapp.ActiveCell;
Excel.Workbook wbook = xlapp.ActiveWorkbook;
currentSheet = wbook.ActiveSheet;
/* Insert to the current cell where the cell-function is being executed. */
return "Hello, world";
}
}
}