Script lab shows examples of how to get a range using rows, columns and cell values here: https://learn.microsoft.com/en-us/office/dev/add-ins/excel/excel-add-ins-ranges-advanced

However, all the values in examples were hardcoded. I could not find on any page any example of how to use variables in the get range? Maybe its a simple javascript thing but I am totally new to it. Can anyone share an example of how to do say? sheet.getRange("4:9") using variables for number 4 and number 9?

And if you do know that answer for above, can you also share, how to do this using cell references in the below example?

Assume that I can find the values of rows and column names and set them in some variables. How would I use it in below code replacing the values for G1, A1 and E1? sheet.getRange("G1").copyFrom("A1:E1");

Thanking you in advance for your help!

P.S: I already tried searching on stack overflow with keywords for "script lab range variables" but found no answers. Hence asking here.

Excel.run(function (context) {
    var sheet = context.workbook.worksheets.getItem("Sample");

    // Group the larger, main level. Note that the outline controls
    // will be on row 10, meaning 4-9 will collapse and expand.
    sheet.getRange("4:9").group(Excel.GroupOption.byRows);

    // Group the smaller, sublevels. Note that the outline controls
    // will be on rows 6 and 9, meaning 4-5 and 7-8 will collapse and expand.
    sheet.getRange("4:5").group(Excel.GroupOption.byRows);
    sheet.getRange("7:8").group(Excel.GroupOption.byRows);

    // Group the larger, main level. Note that the outline controls
    // will be on column R, meaning C-Q will collapse and expand.
    sheet.getRange("C:Q").group(Excel.GroupOption.byColumns);

    // Group the smaller, sublevels. Note that the outline controls
    // will be on columns G, L, and R, meaning C-F, H-K, and M-P will collapse and expand.
    sheet.getRange("C:F").group(Excel.GroupOption.byColumns);
    sheet.getRange("H:K").group(Excel.GroupOption.byColumns);
    sheet.getRange("M:P").group(Excel.GroupOption.byColumns);
    return context.sync();
}).catch(errorHandlerFunction);
1

There are 1 best solutions below

0
On

So, I got an answer on this here: https://github.com/OfficeDev/office-js-docs-pr/issues/1699

Thanks to AlexJerabek (you can find his id on the above github link).

In summary: The getRange method takes in a string representing a cell range in the worksheet, such as "A1:D4", "A:D" for just the columns, or "1:4" for just the rows. As long as your variables map to Excel rows or columns, you can use string concatenation to build the argument. You may need to use range.columnIndex, range.rowIndex, and range.getCell to translate to and from zero-based numbers into the letter-based columns.

Based on this answer, I tried below (and it worked):

const sheet = context.workbook.worksheets.getActiveWorksheet();
var firstrow = 1
var lastRow = 6
var range = sheet.getRange(firstrow + ":" + lastRow)