There are some inaccuracies in your code. I will try to guide you through the code.
- Your code alone will not work, but you probably know that
- first declare the active sheet (or spreadsheet)
var sh = SpreadsheetApp.getActiveSheet();
- determine the last row in the sheet
var row = sh.getLastRow();
- get the range and get the values
var aData = sh.getRange(1, 2, row, 1).getValues();
- The
getRange(row, col)
will range a particular cell and not a range. After having set the getRange()
, you need to get the content by adding the getValues()
. The setFormula()
is specifically meant for adding a formula, like "=MAX(A:A)"
.
Here's the ittaration, how I would perform it:
- first, you need to hold the "new" data in an array
var aNew = new Array();
- set up the itteration
for (i=0; i<aData.length; i++) {
- set up an
IF
statement
if(aData[i][0] != "") {
- add "new" data into array via the push method
aNew.push([i+1]);
- Finally add the newly gathered data to the active sheet. This is done via the
setValues()
command.
sh.getRange(1, 1, aNew.length, 1).setValues(aNew);
The complete code and example file: itteration code
function myFunction() {
var sh = SpreadsheetApp.getActiveSheet();
var row = sh.getLastRow();
var aData = sh.getRange(1, 2, row, 1).getValues();
var aNew = new Array();
for (i=0; i<aData.length; i++) {
if(aData[i][0] != "") {
aNew.push([i+1]);
}
}
sh.getRange(1, 1, aNew.length, 1).setValues(aNew);
}