I created my first function in google sheets. Basically I got it to work the way I want it to but it hits a max execution time limit. I posted the code below, I'm sure there are a few ways to optimize it so it can run faster.
The code basically cycles through records in a sheet to add image filenames. There are six image filenames per product and sometimes I need to add new rows to list all the filenames, like in the following screenshot:
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getDataRange();
var values = range.getValues();
var c = 1;
for (var i=1; i<values.length; i++) {
c = 1;
do {
c = c + 1;
i = i + 1;
} while (values[i+1][13] == values[i][13]);
while (c < 6) {
sheet.insertRowsAfter(i+1,1);
c = c + 1;
i = i + 1;
sheet.getRange(i+1,1).setValue(values[i-1][0]);
}
range = sheet.getDataRange();
values = range.getValues();
if(c <= 6) {
sheet.getRange(i-4,25).setValue(values[i-5][13] + "_main.jpg");
sheet.getRange(i-3,25).setValue(values[i-5][13] + "_detail.jpg");
sheet.getRange(i-2,25).setValue(values[i-5][13] + "_detail1.jpg");
sheet.getRange(i-1,25).setValue(values[i-5][13] + "_detail2.jpg");
sheet.getRange(i,25).setValue(values[i-5][13] + "_side.jpg");
sheet.getRange(i+1,25).setValue(values[i-5][13] + "_back.jpg");
}
if(c > 6) {
sheet.getRange(i-c+2,25).setValue(values[i-c+2][13] + "_main.jpg");
sheet.getRange(i-c+3,25).setValue(values[i-c+2][13] + "_detail.jpg");
sheet.getRange(i-c+4,25).setValue(values[i-c+2][13] + "_detail1.jpg");
sheet.getRange(i-c+5,25).setValue(values[i-c+2][13] + "_detail2.jpg");
sheet.getRange(i-c+6,25).setValue(values[i-c+2][13] + "_side.jpg");
sheet.getRange(i-c+7,25).setValue(values[i-c+2][13] + "_back.jpg");
}
}