Question

I've been trying to make a function that will go down a list(a range) and do nothing if it has something in the cell, but if the cell is blank it will input value "Lunch" then stop. Leaving all the cells below it alone. Right now when I use the code bellow it will do nothing to the cells that have something in it(Like I want), but will continue down the list writing Lunch on each empty cell, instead of stopping on the first empty cell. I also tried return statement instead of break and that would only make the first cell, if empty, 'Lunch' but if that first cell had something in it, it would do nothing. What am I doing wrong? Thanks in advance!

function Lunch1()
{
    var range = SpreadsheetApp.getActiveSheet().getRange('M3:N19'),
    numRows = range.getNumRows(),
    numCols = range.getNumColumns();
    for (var i = 1; i <= numRows; i++)
    {
        for (var j = 1; j <= numCols; j++)
        {
            var currentValue = range.getCell(i,j).getValue(),
            Lunch = "LUNCH";

            if (currentValue == "")
            {
                range.getCell(i,j).setValue(Lunch).setBackground('purple');  
                break;    
            } 
        }
    }
}
Was it helpful?

Solution

You need to stop function execution after your condition executes. Use return for this purpose rather than break

if (currentValue == "")
{
      range.getCell(i,j).setValue(Lunch).setBackground('purple');  
      return;    
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top