Loop through columns looping through rows
That is because the loop occurs in the array of arrays you get with getValues()
in which each rows content is represented by an array of column values.
To iterate on a row just use data[0]
and loop into it.(data[0][0]
, data[0][1]
, data[0][n]
...)
Values from other rows will be in data[1][n]
, data[2][n]
etc., n being the loop index
Note also that you selected a range made of 2 rows and you mention in your question that you need data from 2,3 and 4... so adjust the range to necessary size.
Code example:
var data = dataRange.getValues();
for (n in data[0]) {
var emailAddress = data[0][n]; // First row in each column
var message = data[1][n]; // Second row in each column
var subject = "Sending emails from a Spreadsheet";
MailApp.sendEmail(emailAddress, subject, message);
}
user3873364
Updated on July 09, 2022Comments
-
user3873364 almost 2 years
I'm trying to create a script that loops through columns and set variables from rows 2, 3 and 4. I've found the following example script and tried to rewrite it to loop through columns but when I replace "row" with "column" it still loops through rows.
function sendEmails() { var sheet = SpreadsheetApp.getActiveSheet(); var startRow = 2; // First row of data to process var numRows = 2; // Number of rows to process // Fetch the range of cells A2:B3 var dataRange = sheet.getRange(startRow, 1, numRows, 2) // Fetch values for each row in the Range. var data = dataRange.getValues(); for (i in data) { var row = data[i]; var emailAddress = row[0]; // First column var message = row[1]; // Second column var subject = "Sending emails from a Spreadsheet"; MailApp.sendEmail(emailAddress, subject, message); } }
-
onit almost 2 yearsThis is crystal clear!