Search code examples
javascriptoffice-jsscriptlab

How to get the all names (not values) in office.js?


I have several "named" ranges. I am trying to get the name of the ranges, not the values.

I have tried the following :

$("#get-values").click(getValues);

async function getValues() {
    try {
        await Excel.run(async (context) => {
            const sheet = context.workbook.worksheets.getItem("FormName");
            const valm = sheet.names;
            valm.load("names");
            await context.sync();
            console.log(JSON.stringify(valm.names));
        });
    } catch (error) {
        OfficeHelpers.UI.notify(error);
        OfficeHelpers.Utilities.log(error);
    }
}

I don't know how to get the names from the above script


Solution

  • The names collection is accessible at the Workbook level:

    async function run() {
        await Excel.run(async (context) => {
            var names = context.workbook.names;
            names.load();
            await context.sync();
            console.log(JSON.stringify(names));
        });
    }
    

    This is will result in a NamedItemCollection containing NotedItems similar to this:

    {
        "comment": "",
        "name": "Range Name",
        "scope": "Workbook",
        "type": "Range",
        "value": "Sheet1!$A$1:$C$1",
        "visible": true
    }
    

    The address for the range is held in the value property. You can use this to determine which sheet a given range is found.