0

I am trying to save a script to apply a number format to whatever cells I have selected on the worksheet. Recording the script is easy, but it only applies to whatever cell I am in at the time. However, I could be in a different cell or I may need to apply the format to a range of cells.

This is a copy of my script at the moment but it is only being applied to cell E8, whereas I want it to run on whatever cells I have selected at the time.

Function main(workbook: ExcelScript.Workbook) {
    let selectedSheet = workbook.getActiveWorksheet();
Set format for range E8 on selectedSheet
    selectedSheet.getRange("E8").setNumberFormatLocal("#,##0;(#,##0);-");
}

I am not sure what I need to replace E8 with to get it to apply to other cells.

1 Answer 1

1

There is a method called getSelectedRanges() that allows you to target the selected range. Here is how you can use it in your case:

function main(workbook: ExcelScript.Workbook) {
    let selectedSheet = workbook.getActiveWorksheet();
    let selectedRange = selectedSheet.getSelectedRanges();
    for(let range of selectedRange){
        range.setNumberFormatLocal("#,##0;(#,##0);-")
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your reply. I am still doing something wrong as I have an error message.
function main(workbook: ExcelScript.Workbook) { let selectedSheet = workbook.getActiveWorksheet(); let selectedRange = selectedSheet.getSelectedRanges(); range.setNumberFormatLocal("#,##0;(#,##0);-"); }
It says "see line 3, column 6: office scripts cannot infer the data type of this variable. Please declare a type for the variable.
@EmmaEmerson You forgot the for(let range of selectedRange){}. The script is: function main(workbook: ExcelScript.Workbook) { let selectedSheet = workbook.getActiveWorksheet(); let selectedRange = selectedSheet.getSelectedRanges(); for(let range of selectedRange){range.setNumberFormatLocal("#,##0;(#,##0);-")}} The range variable is set in the for loop :)

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.