为什么创建的名称范围无法获取命名项目范围?

Why created name range not able to get named item range?

我尝试从工作簿中的命名项读取范围,但出现错误:

This operation is not permitted for the current object.

首先创建名称范围(在名称对象上使用 add() 方法)。

Excel.run(function (ctx) {
    var sheet = ctx.workbook.names.add("MyRange", "Sheet1!A1B2");
    return ctx.sync().then(function () {
        console.log("range name added");
    }).catch(function (e) {        
        console.log("Error Message is -> " + e.message);
    })
});

到目前为止代码工作得很好。现在我想读取现有命名范围的范围。所以我对我的代码做了一些修改:

Excel.run(function (ctx) {
    var sheet = ctx.workbook.names.add("MyRange", "Sheet1!A1B2");
    return ctx.sync().then(function () {
        console.log("range name added");
        var range = ctx.workbook.names.getItem("MyRange").getRange();
        range.load("address");
        return ctx.sync().then(function () {
            console.log(range.address);
        });
    });
}).catch(function (e) {
    console.log("Error Message is -> " + e.message);
});

当我尝试 运行 这段代码时,我得到了上面的错误。我使用了 Office.js API.

中提到的相同方法

似乎您用来创建命名项的语法(即传递一个字符串作为第二个参数而不是传递一个 Range 对象)使得您正在创建的命名项不是'它实际上不是一个 Range 对象。因此,当您随后尝试将该命名项视为 Range 对象时,您会收到错误消息。

这是一个代码片段,它为一个范围创建一个命名项,然后获取该命名项(一个范围)并将其地址写入控制台:

Excel.run(function (ctx) {

    // Create named item "MyRange" for the specified range.
    var sheet = ctx.workbook.worksheets.getItem("Sample");
    var myRange = sheet.getRange("A1:E1");
    sheet.names.add("MyRange", myRange);

    return ctx.sync()
        .then(function () {

            // Get the range for the named item "MyRange" and load its address property.
            var myNamedItem = sheet.names.getItem("MyRange");
            var range = myNamedItem.getRange();
            range.load("address");

            return ctx.sync()
                .then(function () {
                    console.log("Address of range: " + range.address);
                });
        });
});

您可以在 Excel 中使用 Script Lab (https://aka.ms/getscriptlab). Simply install the Script Lab add-in (free), then choose "Import" in the navigation menu, and use the following GIST URL: https://gist.github.com/kbrandl/89706cb9808bd7815eb0c89930ce526c.

自己快速轻松地尝试此代码片段