A simple google spreadsheet for each loop?

It's been a long time since I coded. I have never looked at scripts for google spreadsheets before. I just want to make a simple effect for editing a spreadsheet. If I understand correctly, is this doable as long as you run it manually?

The syntax throws me off too much. My main goal is to set every cell in a fixed range of columns equal to itself plus the value in the adjacent column, and then set that second value to 0.

My instinct would be to do something like

CellRange[i][j] selected = C9:D13;
for(i=0,i<selectedrange.length,i++){
SpreadsheetApp.getActiveRange().setValue(selected[i][j]+selected[i][j+1];
SpreadsheetApp.getRange(selected[i][j+1]).setValue(0);
}

      

This may be terribly wrong, but I feel like I should at least drop my best guess before seeking help.

+1


source to share


1 answer


Let's say the goal is to process the range C9: D13 by adding the value in D to the value in C and then setting D to zero. The code will look like this:

function addColumns() {
  var sheet = SpreadsheetApp.getActiveSheet(); // or getSheetByName
  var range = sheet.getRange("C9:D13");
  var values = range.getValues();
  for (var i = 0; i < values.length; i++) {
    values[i][0] = values[i][0] + values[i][1];
    values[i][1] = 0;
  }
  range.setValues(values);
}

      



Here values[i][0]

means the values ​​of the first column in the range in which we are working (namely C), and values[i][1]

refers to the second. JavaScript array indexing starts at 0, as opposed to row numbering in spreadsheets.

+1


source







All Articles