Detecting a relative range name; difference between VS code and Script lab

Jan Karel Pieterse 1 Reputation point MVP
2024-11-22T15:49:50.8633333+00:00

I am updating some of my code of my Name Manager add-in. I've discovered something odd.

Background:

If you define a name in Excel like so:

Select cell A2, now define this name:

Name: test

refers to: =Sheet1!A1

the cell the name points to depends on the cell you use that name in. Select cell A2 and the name points to A1. Select B3 and the name will point to B2 (both the row and the column reference are relative).

In VBA if you retrieve the refersto property of the name, you get a different answer depending on the active cell.

In office-js, the experience is mixed.

If I use this code in Script lab:

$``("#run").on("click", () => tryCatch(run));

async`` function run() {

  ``await Excel.run(async (context) => {

    ``const nm = context.workbook.names.getItem("test").load("formula");

    ``await context.sync();

    console``.log(nm.formula);

    context``.workbook.getActiveCell().getOffsetRange(1, 0).select();

    ``const nm1 = context.workbook.names.getItem("test").load("formula");

    ``await context.sync();

    console``.log(nm1.formula);

  ``});

}

/** Default helper for invoking an action and handling errors. */

async`` function tryCatch(callback) {

  ``try {

    ``await callback();

  ``} catch (error) {

    ``// Note: In a production add-in, you'd want to notify the user through your add-in's UI.

    console``.error(error);

  ``}

}

then I get two different formulas in the console, the second one differing one row from the first, for example:

Sheet1!A1

Sheet1!A2

If I do exactly the same in my VS Code project, I get two identical formulas (Sheet1!A1).

WHY????

Excel
Excel
A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
2,048 questions
JavaScript API
JavaScript API
An Office service that supports add-ins to interact with objects in Office client applications.
1,013 questions
Office Development
Office Development
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Development: The process of researching, productizing, and refining new or existing technologies.
4,103 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.