When you're working on multiple rows and/or columns from spreadsheets, one challenge is converting between indexes and the various ways that cell locations can be expressed.
- In A1Notation, columns are expressed first, as a letter, followed by row, as a number starting at 1.
- R1C1 notation flips the order of rows and columns, and both dimensions are numbers starting from 1.
- Arrays in javascript start from index 0. As you evolve your script to use
getDataRange().getValues()
, this will be important. In the two-dimensional array returned by getValues()
, rows are expressed first, then column, as in data[row][column]
. The upper bound of your loops will need to be adjusted accordingly, and you may need to +1
if you're referencing Range methods like setFormula()
.
The code snippet below will do what you're looking for, as a starting point. I've left out the else
block to reduce noise. Note the use of getA1Notation()
to build the SPLIT
formula dynamically - a straight-forward evolution of your script.
You'll need to define numLastRow
yourself, and since the script is accessing Range methods throughout, 10
would mean cell A10
.
var defSheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1")
for (var x=1; x<=numLastRow; x++) {
var srcRange = defSheet1.getRange(x,1);
var value = srcRange.getValue(); // Get value at Row x, Column 1
if (value.indexOf(",") !== -1) {
var splitCell = '=SPLIT(' + srcRange.getA1Notation() + ',",")';
defSheet1.getRange(x,5).setFormula(splitCell);
}
};