同步自定义函数使评估和条件格式进程能够与自定义函数同时在 Excel 中运行。 当自定义函数需要与本文中列出的任何 Excel 进程同步运行时,启用同步支持。 不支持同步作的自定义函数在与这些 Excel 进程同时运行时返回错误,例如 #CALC! 或 #VALUE! 。
警告
同步自定义函数不支持使用 Office JavaScript API 执行写入作,例如使用 Range.values 设置单元格值。 在同步自定义函数中调用写入作可能会导致 Excel 冻结。
同步自定义函数支持的 Excel 进程
以下作和过程适用于同步自定义函数。
支持的评估作
- 在 Excel 中选择“公式”,然后选择“计算公式”。
- 选择“公式”,然后选择“在 Excel 中插入函数”。
- 在单元格编辑模式下,选择公式的一部分并使用 F9 查看部分计算结果。
-
Application.CalculateVBA 中的 方法。
支持的条件格式作
以下列表适用于由 Excel UI 和 Office JavaScript API 触发的条件格式设置作。
- 创建新规则。
- 编辑规则。
- 删除规则。
- 重新排序规则。
- 更改“应用于”范围。
- 打开或关闭“如果为 true,则停止”。
- 清除所有规则。
- 剪切并粘贴包含条件格式的单元格。
- 复制并粘贴包含条件格式的单元格。
注意
当同步自定义函数需要大量时间才能完成时,Excel 可能会在等待结果时暂时阻止用户界面。 为了避免长时间的中断,用户可以随时使用 Esc 键或选择单元格或对话框外的任意位置来取消函数执行。
在加载项中启用同步支持
若要在外接程序中支持同步方案,请执行以下步骤。
- 如果 自动生成 JSON 元数据,请使用
@supportSyncJSDoc 标记。 - 如果手动创建 JSON 元数据,请使用
"supportSync": truefunctions.json 文件的 对象中的"options"设置。 - 如果函数使用
Excel.RequestContext,则调用setInvocation的Excel.RequestContext方法并传入CustomFunctions.Invocation对象。 有关示例,请参阅 代码示例。
重要
同步自定义函数不能是 流式处理 函数或 可变 函数。 如果将 标记与 或 @streaming 标记一@supportSync起使用@volatile,Excel 将忽略同步支持。 易失性或流式处理支持优先。
代码示例
以下代码示例演示如何创建同步自定义函数。
/**
* A synchronous custom function that takes a cell address and returns the value of that cell.
* @customfunction
* @supportSync
* @param {string} address The address of the cell from which to retrieve the value.
* @param {CustomFunctions.Invocation} invocation Invocation object.
* @returns The value of the cell at the input address.
*/
export async function getCellValue(address, invocation) {
const context = new Excel.RequestContext();
context.setInvocation(invocation); // The `invocation` object must be passed in the `setInvocation` method for synchronous functions.
const range = context.workbook.worksheets.getActiveWorksheet().getRange(address);
range.load("values");
await context.sync();
return range.values[0][0];
}