自定义枚举为用户提供自定义函数的 Excel 自动完成选项。 枚举中的成员在编辑栏中显示为建议。 前面的屏幕截图中的行星是提供设置列表的自定义枚举的示例。 本文介绍如何创建自定义枚举并将其用作自定义函数中的参数。
定义自定义枚举
使用 JSDoc 标记 @customenum定义枚举。 然后,在自定义函数元数据中自动生成相应的 JSON 属性。 有关 JSDoc 标记和自定义函数的详细信息,请参阅 JSDoc 标记的基础知识。
注意
使用 @customenum JSDoc 标记创建的自定义枚举仅在 TypeScript 中受支持。 JavaScript 不支持它们。 若要对 JavaScript 函数使用自定义枚举,必须手动创建自己的 JSON 元数据。 若要了解详细信息,请参阅 手动创建 JSON 元数据。
以下代码片段演示如何定义和使用简单的自定义枚举作为参数。
/**
* A custom enum with descriptions and tooltips.
* @customenum {string}
*/
enum PLANETS {
/** Mercury is the first planet from the sun. */
mercury = "Mercury",
/** Venus is the second planet from the sun. */
venus = "Venus",
/** Earth is the third planet from the sun. */
earth = "Earth",
}
/**
* A sample function that uses the custom enum as a parameter.
* @customfunction
*/
function getPlanets(value: PLANETS): any {
return value;
}
多次使用自定义枚举
自定义枚举可以在多个函数中重复使用,并且可以用作单个函数的多个参数。 一个函数还可以同时将多个枚举作为参数。 枚举参数可以是重复的,也可以是可选的。
下面的代码示例演示了一个 NUMBERS 枚举和一个自定义函数,该函数多次使用该枚举作为输入值。
/**
* Enum of numbers with descriptions and tooltips.
* @customenum {number}
*/
enum NUMBERS {
/** One */
One = 1,
/** Two */
Two = 2,
/** Three */
Three = 3,
/** Four */
Four = 4,
/** Five */
Five = 5
}
/**
* Enter multiple numbers from the NUMBERS enum and get the sum.
* @customfunction
* @param input Enter enum numbers.
* @returns
*/
function addNumbers(input: NUMBERS[]): any {
const sum = input.reduce((acc, num) => acc + num, 0);
return "Sum: " + sum;
}
本地化自定义枚举
本地化自定义枚举类似于 本地化自定义函数。 必须 手动创建 JSON 元数据 ,然后为每种语言创建新的 JSON 元数据文件。
请注意, name 只有枚举中的 和 tooltip 属性应本地化为目标语言。 属性 value 应保持不变,以避免需要在函数体中处理多种语言。
以下 JSON 代码片段显示了水星行星的中文本地化 values 对象。
"enums": [
{
"id": "PLANETS",
"type": "string",
"values": [
{
"name": "水星",
"value": "mercury",
"tooltip": "水星是距离太阳最近的行星"
}
]
}
],
向后兼容
自定义枚举提供向后兼容性。 在旧版 Excel 上,使用自定义枚举的参数作为标准参数工作,而不会显示在 Excel 自动完成列表中。