exceloffice-jsoffice-scripts

How to get last column in specific range in Office Script?


I have values in range A1:E10 and I'd like to get the next empty column in that range (excluding headers). In this case last column used is "C" and next empty column would be "D".

enter image description here

My curren code only gets the last column index in all used range, but I don`t know how to get the last column letter in specific range.

function main(workbook: ExcelScript.Workbook) {

    const mysheet = workbook.getWorksheet("Sheet1");
    const usedRange = mysheet.getUsedRange(true);
    const LastCol = usedRange.getLastColumn().getColumnIndex();

    console.log(Last column: " + LastCol);
}

Solution

  • There probably are better ways but the one I can think about is just to iterate over each column backwards:

    function main(workbook: ExcelScript.Workbook) {
        const mysheet = workbook.getWorksheet("Sheet1");
        const range = mysheet.getRange("A2:E10");
        const columns = range.getColumnCount();
    
        for (let i = 0; i < columns; i++) {
            if (range.getColumn(i).getValues().every(row => row[0] === null || row[0] === "")) {
                console.log("Next empty column: " + String.fromCharCode(65 + i));
                return;
            }
        }
    
        console.log("No empty column found in the specified range.");
    }