Search code examples
exceloffice-js

Select a discontiguous range


I'm building an office-js add-in for Excel. I need to select two non-adjacent cells (e.g A1 and C3). The following code works to select the multi-cell range starting at A1 and ending at C3.

    Excel.run(function (ctx) {
        var sheet = ctx.workbook.worksheets.getItem('sheet1');
        var range = sheet.getRange('a1:c3');
        range.select();
        return ctx.sync(); 
    });

However, I'm looking to select only the two cells (A1 and C3). In VBA the syntax is

worksheets("sheet1").range("a1,c3").select

But I cannot find anything analogous in office-js. I've tried as similar syntax with office-js:

Excel.run(function (ctx) {
        var sheet = ctx.workbook.worksheets.getItem('sheet1');
        var range = sheet.getRange('a1,c3');
        range.select();
        return ctx.sync(); 
});

but it fails with: {"code":"InvalidArgument","message":"The argument is invalid or missing or has an incorrect format.","errorLocation":"Worksheet.getRange"}


Solution

  • Actually on the latest insiders fast (16.0.9327.2006 ) deployed just a few days ago you can actually try our implementation for Areas (aka discontinuous ranges. )

    please make sure to use our preview cdn to test this.(https://appsforoffice.microsoft.com/lib/beta/hosted/office.js)

    but basically you can do things like:

    function run() {
        return Excel.run(function (context) {
            var range = context.workbook.getSelectedRange();
            range.load("address");
            return context.sync()
                .then(function () {
                    console.log("The range address was \"" + range.address + "\".");
                });
        });
    }

    and you will see that if you select a non-continuous range you will get something like: "Sheet1!C6:C14,Sheet1!F12:H22".

    you can pass a similar string on the getRange method to create an Area and simultaneously format it etc.

    Please give it a try and send us your feedback! thanks!