Keep running or stop the code in a specific section using office script in an excel report

When I write a script, it may happen that I need to stop my code for a specific section or to keep it running. For instance, my script includes 3 sheets and I want a specific section of the code to run only for 2 sheets. For that, I have to use “break” (stop temporary) and “return” (stop permanently).

 

When I use the script ?

To stop my code to run for a specific section.

 

How to create the script ?

Read How to create, edit and select an Office Script in an excel report

 

How to create the button to associate it with the script ?

Read How to create a button and associated it to an Office Script in an excel report

 

How is/are the script(s) ?

Copy the code below and paste it into your script. You will see my comments in green if exist so follow the help to adapt to your need.

Example of return (stop permanently)

In this example, only the “yourcodereturn” section will run and it will stop once finished meaning that the “yourcodebreak” section will not run.


function main(workbook: ExcelScript.Workbook) {
    yourcodereturn;
    for (let i = 0; i < valuesreturn.length; i++) {
        if (yourcodereturn) {
            yourcodereturn;
            return;
        }
    }
    yourcodebreak;
    for (let i = 0; i < valuesbreak.length; i++) {
        if (yourcodebreak) {
            yourcodebreak;
            break;
        }
    }
}              
              

Example of break (stop temporary)

In this example, the full code will run and it will stop once completed the “yourcodereturn” section.


function main(workbook: ExcelScript.Workbook) {
    yourcodebreak;
    for (let i = 0; i < valuesbreak.length; i++) {
        if (yourcodebreak) {
            yourcodebreak;
            break;
        }
    }
    yourcodereturn;
    for (let i = 0; i < valuesreturn.length; i++) {
        if (yourcodereturn) {
            yourcodereturn;
            return;
        }
    }
}             
              

Interesting Topics