1

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);
}

2 Answers 2

1

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.");
}

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help. In my actual data the range goes from E6:BX53 but for example if the column index of last colum is 39, the convertion of String.fromCharCode(65 + 39) is givinh me column H and should be column AM
1

I know it's already answered but like the answer says, there are better ways ...

function main(workbook: ExcelScript.Workbook) {
    let selectedSheet = workbook.getActiveWorksheet();
    let rangeToGetColumnLetterFrom = selectedSheet.getRange("A2:E10").getUsedRange();

    let lastColumnLetterInRangeAddress = rangeToGetColumnLetterFrom.getLastCell().getEntireColumn().getOffsetRange(0,1).getAddress();
    let lastColumnLetterInRange = lastColumnLetterInRangeAddress.split('!')[1].split(':')[0]
    
    console.log(lastColumnLetterInRange);
}

... you can take the above approach which is a lot more direct.

You just need to define the range you want to work with.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.