Search code examples
javascriptoffice-jsexcel-addins

Merging excel cells using office.js


I am trying to merge some cells using the Office.js API as stated in the question. I created a new web add in project using visual studio. I kept the generated project as is, and add a button with a click handler to merge the cells here is the code of the event handler.

function mergingCells() {
   Excel.run(function (ctx) {
   var sheet = ctx.workbook.worksheets.getActiveWorksheet();
   var range = sheet.getRange('A1:D2');
   range.merge(false);
   return ctx.sync().then(function () {
   showNotification('Merging done',
   'Merged range is ' + range.address);
   });
   }).catch(errorHandler);
}

the error that I get is : error

the expected result : The expected result


Solution

  • There was an error in your code in terms of not loading the range address in the .then. But if I remove the range.address, or call range.load("address") before the sync, the code does work.

    One thing I'm wondering: what version of Office are you using? If you are using Office 2016 RTM (not subscription-based Office 365), the merge method might just not be available (it's only part of ExcelApi 1.2, not ExcelApi 1.1 that shipped with RTM).

    You can see what API set a particular API belongs to in the IntelliSense:

    IntelliSense

    See https://dev.office.com/docs/add-ins/develop/office-versions for more info on the Office version/flavors.

    See https://dev.office.com/docs/add-ins/develop/office-js-versioning for more info on Office JS versioning and requirement sets.

    The RTM version of Office 2016 unfortunately did not differentiate between API not available and some of the other errors; so they both come across as InvalidArgument (but not for versions thereafter).