Loop through columns looping through rows

孤者浪人 提交于 2021-01-28 01:52:20

问题


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);
  }
}

回答1:


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);
}


来源:https://stackoverflow.com/questions/24936660/loop-through-columns-looping-through-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!