Why can't the created name range get the named range of elements?

I tried to read a range from a named element in a workbook, but I get an error:

This operation is not allowed for the current object.

First of all, the created range of names (using the method add()for the name object).

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);
    })
});

So far, the code has worked very well. Now I want to read a range for an existing named range. So I made some changes to my code:

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);
});

When I try to run this code, I get the error above. I used the same method as in the Office.js API.

+4
source share
1 answer

, (.. 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). Script Lab (), "" URL- GIST: https://gist.github.com/kbrandl/89706cb9808bd7815eb0c89930ce526c.

+2

Source: https://habr.com/ru/post/1689049/


All Articles