1
votes

I am doing my first loop in Google Script and it isn't working properly. It's kind of only half working so I have no idea what is the issue.

The code is supposed to loop down each row and in column 1 and enter the next ID number (and once it has done that it should increase the LastID number by 1 and then put this on the next row).

The problem is that it enters the LastID in each of the cells and then at the end it increased the LastID by 1 (So lets say the LastID was 1, it puts 1 in all the cells instead of 2,3,4 etc..)

(Note I have left out a bit of the code declaring the sheet variables etc..)

function myFunction() {
    var IDCount = 1;
    var LastID = 1;
    var RowCount = 4;

    {
        for (var x = IDCount; x < RowCount; x++)
            Browser.Buttons.YES_NO);

    sheet.getRange((x + 2), 1).setValue(LastID) //set next row with missing ID number

    sheet.getRange(2, 7).setValue(LastID) //set the new ID
    LastID++ //Increase LastID by 1

}
}

Hope someone can help .Thanks

1

1 Answers

1
votes

You have not defined the body of loop. If we don't provide braces, by default it's assumed that only one line is there in body. So in your case this is happening. It's assuming only

sheet.getRange((x+2), 1).setValue(LastID) //set next row with missing ID number

is within loop, so it's setting same value to all rows.

Try this code :

function myFunction() {
    var startRow = 1; // You can set your start row number here
    var startId = 1; // You can set your start id number here
    var lastRow = 4; // You can set your last row number here, till where you want to set id;
    //if you want this to be last row of sheet then = sheet.getLastRow();
    var tempId = startId;
    for (var x = startRow; x <= lastRow; x++) {
        sheet.getRange(x, 1).setValue(tempId) //set the ID number
        tempId++; // Increment the ID by 1
    }
}