ezuk ezuk - 1 month ago 14
Javascript Question

Google Spreadsheets: Iterate over range, append string to each

I have a range of cells selected in a Google Spreadsheet (activerange).

I want to iterate over every cell in that range, and add a string to the end. The string is always the same, and can be hardcoded into the function.

It seems like a really simple thing, but I've been messing with the code for an hour now and can't get anything useful to happen, and the docs are really not helping.

Here's what I have now. I don't code JS (I do know VBA, for all that helps..).

function appendString() {
var range = SpreadsheetApp.getActiveSheet().getActiveRange();
for (var i = 0; i < range.length; i++) {
var currentValue = range[i].getValue();
var withString = currentValue + " string";
range[i].setValue(withString);
}
}


Any help would be most appreciated.

Answer

You can try something like this:

function appendString() {
  var range = SpreadsheetApp.getActiveSheet().getActiveRange();
  var numRows = range.getNumRows();
  var numCols = range.getNumColumns();
  for (var i = 1; i <= numRows; i++) {
    for (var j = 1; j <= numCols; j++) {
      var currentValue = range.getCell(i,j).getValue();
      var withString = currentValue + " string";
      range.getCell(i,j).setValue(withString);
    }
  }
}