sagar
sagar

Reputation: 464

Office.js | Excell add in | get selected cell address on click

I am working on a Excel Web Add-In using Office.js. I need to get selected cell's Address with below scenario:

  1. Open the Excel, Don't load add-in, click on any Cell in excel worksheet area. eg:A4
  2. Load the add-in.
  3. Again click on the same cell number eg:A4 that was highlighted on worksheet area as before loading add-in we selected.

Its not triggering the below code:

Office.context.document.addHandlerAsync(Office.EventType.DocumentSelectionChanged,
        function (eventArgs) {
            Excel.run(function (ctx) {
                var range = ctx.workbook.getSelectedRange();
                range.load(['address', 'values']);
                return ctx.sync().then(function () {
                    showNotification("", range.values[0][0] + " Address:" + range.address);
                });
            });                    
        });

NOTE: If I select cell Id other than previously selected cell id eg.A5 its working. Even again if I try to select from cell id A5 to previously selected cell id A4 its working. Only if we try to select same cell its not triggering the event. Spend lots of time can some one please help or its limitation in microsoft excel?

Upvotes: 1

Views: 1175

Answers (1)

Raymond Lu
Raymond Lu

Reputation: 2236

I think this is by design, as you are listening to SelectionChanged event, if the current selection is A4, and you click A4, it would not trigger the event as you didn't change the selection.

I am not sure your scenario, if you want to show the current selection, you could add the code before register the event. here is a sample code

async function run() {
  await Excel.run(async (context) => {
    var range = context.workbook.getSelectedRange();
    range.load();
    await context.sync();
    console.log(range);
    Office.context.document.addHandlerAsync(Office.EventType.DocumentSelectionChanged, showSelection);
  });
}

async function showSelection(){
  Excel.run(async (context) => {
    var range = context.workbook.getSelectedRange();
    range.load();
    await context.sync();
    console.log(range);
  });
}

Upvotes: 2

Related Questions