遍历列遍历行 [英] Loop through columns looping through rows

查看:56
本文介绍了遍历列遍历行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个脚本,该脚本遍历各列并设置第2、3和4行中的变量.我找到了以下示例脚本,并尝试将其重写为遍历各列,但是当我替换"row"时使用列",它仍然在行中循环.

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

推荐答案

这是因为循环发生在使用 getValues()获得的数组的数组中,其中每行的内容都由一个列值数组.

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.

要在一行上进行迭代,只需使用 data [0] 并循环到其中.( data [0] [0] data [0] [1] data [0] [n] ...)

To iterate on a row just use data[0] and loop into it.(data[0][0], data[0][1], data[0][n]...)

其他行中的值将位于 data [1] [n] data [2] [n] 等中,n为循环索引

Values from other rows will be in data[1][n], data[2][n] etc., n being the loop index

还请注意,您选择了一个由2行组成的范围,并在问题中提到需要2、3和4中的数据...因此请将范围调整为必要的大小.

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.

代码示例:

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

这篇关于遍历列遍历行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆