I'm a bit new to the Google scripting scene. I've gone over this so many times and I can't wrap my brain around incrementing properly.
I've created a Google Spreadsheet that uses a form. When someone uses the form to submit equipment, it's going to use a Send Email function (MailApp.sendEmail) to e-mail it to the accounting people.
So far, I can populate the spreadhsheet perfectly, but when the function runs, it only labels the 'status' variable in the 1st row and doesn't continue through the list, then it e-mails that 1 row several times. Can anyone see where I'm going so wrong on this?
I need this to submit the data to the next row that available, then the script checks the last cell for EMAIL_SENT and if it doesn't have that value, I need it to send an e-mail and then check the next row of data as well (in case I need to manually run the script from within the spreadsheet). I couldn't find a similar question on here where I could understand what I'm doing wrong with the incrementing and looping.
Here's the script:
function sendThisOut() {
// set the current spreadsheet and active sheet
var sheet = SpreadsheetApp.getActiveSheet();
// set range data
var sRow = 2; // first top left cell of data
var cols = 9; // Num of cols
// define initial data source and get values
var dataRange = sheet.getRange(sRow,1,1,cols);
var data = dataRange.getValues();
// increment data
for (var i = 0; i < data.length; ++i) {
var row = data[i];
// define each column
var tstamp = row[0]; // get timestamp (col A)
var acct = row[1]; // define account (col B)
var cname = row[2]; // define client name (col C)
var comment = row[3]; // define comments (col D)
var item1 = row[4]; // defines item 1 (col E)
var item2 = row[5]; // defines item 2 (col F)
var item3 = row[6]; // defines item 3 (col G)
var item4 = row[7]; // defines item 4 (col H)
var status = row[8]; // get status (emailed or no?)
// setup e-mail vars
var emailAddr = "myEmail@myDomain.com";
var subject = "ACCT:" + acct + " " + cname + " - Equipment Request";
// setup content of e-mail
var body = "Hello Accounting,
" +
"Please bill for the contained items on the following account:
" +
"Account: " + acct + "
" +
"Client Name: " + cname + "
" +
"Item 1: " + item1 + "
" +
"Item 2: " + item2 + "
" +
"Item 3: " + item3 + "
" +
"Item 4: " + item4 + "
" +
"Reason for rekey: " + comment;
// check status and if it doesn't have EMAIL_SENT, email it
if (status != "EMAIL_SENT") {
MailApp.sendEmail(emailAddr, subject, body);
// Make sure the cell is updated right away in case the script is interrupted
sheet.getRange(sRow + i, 9).setValue(EMAIL_SENT);
SpreadsheetApp.flush();
};
};
}
Thanks for your time!
See Question&Answers more detail:os