How to identify the Excel Sheet changed event in o

2019-03-01 18:11发布

We have an Excel office js add-in written on angular. It has different functionalities based on the sheet the user is in. When users switch the sheets of excel, how can the application know it, so it can change the UI to match the sheet's functionalities?

标签: office-js
3条回答
家丑人穷心不美
2楼-- · 2019-03-01 18:20

You can add handler for context.workbook.worksheets.onActivated

Excel.run((context) => {
  context.workbook.worksheets.onActivated.add(({ worksheetId }) => {
    console.log('Selected worksheet', worksheetId)
  })

  return context.sync()
    .then(function () {
        console.log("Event handler successfully registered");
    });
}).catch(errorHandlerFunction);

More info here

查看更多
\"骚年 ilove
3楼-- · 2019-03-01 18:36

UPDATE May 18 2017: With ExcelApi 1.2+, you can use a new syntax

The new syntax is as follows: context.workbook.onSelectionChanged.add(yourHandler);

You can find a full sample by using Script Lab, a free add-in for trying out Office Add-in snippets. One of the samples has a "Selection Changed" event snippet:

Script Lab samples list

==================

Original answer:

As Michael Saunders said, you can use the selection change event. See the code below. Note that in this case I'm mixing the "Office 2013" syntax with the newer host-specific ("Excel." namespace) syntax of Office 2016. In the "ExcelApi 1.3" release that's coming in a couple months, we actually have a way for you to do this entirely using the new syntax, but that is currently only on the preview CDN, and may not work on your machine, depending on how recent your version of Ofice 2016 is. The code below, meanwhile, is going to work on any 2016 installation, RTM included.

Office.context.document.addHandlerAsync(Office.EventType.DocumentSelectionChanged, function() {
    Excel.run(function(context) {
        var sheet = context.workbook.worksheets.getActiveWorksheet();
        sheet.load("name")
        return context.sync().then(function() {
            console.log('You are now on sheet "' + sheet.name + '"');
        })
    }).catch(function(error) {
        console.log(error);
        if (error instanceof OfficeExtension.Error) {
            console.log("Debug info: " + JSON.stringify(error.debugInfo));
        }
    });    
});
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-03-01 18:40

There isn't a sheet-changed event. However, one workaround would be to subscribe to DocumentSelectionChanged events, then check the user's active sheet each time to see if it changed.

查看更多
登录 后发表回答