在 Excel 中将数据类型与自定义函数配合使用

Excel 数据类型允许自定义函数接受和返回字符串、数字、布尔值和错误以外的值。 例如,自定义函数可以返回格式化数字或接受实体值作为参数。

自定义函数和 Excel JavaScript API 对数据类型使用相同的 JSON 架构。 启用后,Excel 将维护该架构,因为自定义函数计算和计算值。

尝试使用数据类型的自定义函数

在 Excel 中安装Script Lab,然后运行示例库中的“数据类型:自定义函数”示例。

自定义函数如何处理数据类型

自定义函数可以接受数据类型作为参数,并将数据类型创建为返回值。 有关可用类型的简介,请参阅 Excel 外接程序中的数据类型概述。

注意

自定义函数不支持数据类型提供的增强错误对象的完整功能。 自定义函数可以接受数据类型错误对象,但它不会在整个计算过程中维护错误。 目前,自定义函数仅支持 CustomFunctions.Error 对象中包含的错误。

为自定义函数启用数据类型

自定义函数项目包括 JSON 元数据文件,该文件不同于数据类型 API 使用的 JSON 架构。 若要为自定义函数启用数据类型,请手动将 属性添加到 allowCustomDataForDataTypeAny 自定义函数元数据文件,并将其设置为 true。

"allowCustomDataForDataTypeAny": true

有关手动 JSON 元数据创建过程的完整说明,请参阅 手动为自定义函数创建 JSON 元数据。 有关此属性的其他详细信息,请参阅 allowCustomDataForDataTypeAny。

输出带格式的数字

以下自定义函数接受数字和数字格式,然后返回带格式的 DoubleCellValue 对象。

/**
 * Take a number as the input value and return a double as the output.
 * @customfunction
 * @param {number} value
 * @param {string} format (e.g. "0.00%")
 * @returns A formatted number value.
 */
function createFormattedNumber(value, format) {
    return {
        type: "Double",
        basicValue: value,
        numberFormat: format
    };
}

输入实体值

以下自定义函数接受 EntityCellValue 对象和属性名称。 当 为 text时attribute,它将返回实体的 text 属性。 否则,它将返回 basicValue 所请求属性的 。

重要

在自定义函数中构造或返回 EntityCellValue 时,该值包含嵌套实体,仅定义 referencedValues 根级实体上的 数组。 在referencedValues嵌套实体上定义会导致 Excel 返回 #VALUE!错误,没有 JavaScript 异常或详细诊断。 改用嵌套实体中的 ReferenceCellValue 索引指向根实体的 referencedValues 数组。 有关详细信息,请参阅 实体值。

/**
 * Accept an entity value data type as a function input.
 * @customfunction
 * @param {Excel.EntityCellValue} value
 * @param {string} attribute
 * @returns {any} The text value of the entity.
 */
function getEntityAttribute(value, attribute) {
    if (value.type === "Entity") {
        if (attribute === "text") {
            return value.text;
        } else {
            return value.properties[attribute].basicValue;
        }
    } else {
        return JSON.stringify(value);
    }
}

另请参阅