2

I am working on a Excel Web Add-In using Office.js. I need to get selected cell's Address and Value. Please be clear that here user will select only one cell.

This should happen when user click on cell in worksheet.

user3881465
  • 239
  • 2
  • 5
  • 19

2 Answers2

4

The following code example shows how you can get the range of cells that the user has selected, then get the value of the first cell in that range, then display both the address of the selected range and the value of the first cell in that range:

await Excel.run(async (context) => {
    var range = context.workbook.getSelectedRange();
    range.load(['address', 'values']);
    await context.sync();

    var firstSelectedCellValue = range.values[0][0];

    OfficeHelpers.UI.notify('Selected range is: ' + range.address + '. Value of first cell in that range is: ' + firstSelectedCellValue);
});

You can quickly and easily try this snippet yourself by using 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/39a15d790bf9653dda35b52966faed1e.

Kim Brandl
  • 13,125
  • 2
  • 16
  • 21
  • Is `Async` and `await` available in `Office.JS`? – user3881465 Jul 27 '17 at 22:05
  • `async/await` is a concept coming to JavaScript as part of ES7; but it's also something you can use today if you use a tool like TypeScript. In addition to better IntelliSense and compile-time safety, TypeScript allows you to use future language features that it then compiles down to plain ol' ES5 JavaScript that you can execute in the browser. You can find more info in the book ["Building Office Add-ins using Office.js"](https://leanpub.com/buildingofficeaddins/), which describes and uses TypeScript throughout, but also offers "Appendix A: Using plain ES5 JavaScript (no `async/await`)" – Michael Zlatkovsky - Microsoft Jul 29 '17 at 04:32
  • Thanks Kim Brandl for your answer and for providing good information. Thanks @Michael Zlatkovsky – user3881465 Jul 29 '17 at 11:34
1

I solved my problem by following 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);
                    });
                });                    
            });
user3881465
  • 239
  • 2
  • 5
  • 19