遍历有数据和无数据的行

时间:2019-07-01 19:14:46

标签: google-apps-script

我有一个Sheet(1),它将在另一个包含数据的sheet(2)上查找行。如果Sheet(2)中的行有数据,则它们的信息将填充在Sheet(1)中。我需要一个循环来对Sheet(1)中的行进行操作,并能够跳过许多空白行以获取下一组信息。

我有一个循环,该循环将遍历数据的最后一行,但是它将遍历所有带有信息的行,直到出现空白行。我需要一些将通过空白行来继续查找包含数据的行。

function sendEmails() {
var sheet = SpreadsheetApp.getActiveSheet();
var startRow = 2; // First row of data to process
var lastRow = sheet.getLastRow(); // Number of rows to process
// Fetch the range of cells A2:B2
var dataRange = sheet.getRange(2, 1, lastRow-1, 6);
// Fetch values for each row in the Range.
var dataRangee = sheet.getRange("D2");
var qdate = dataRangee.getDisplayValues(); 
var dataRangeee = sheet.getRange("E2");
var ddate = dataRangeee.getDisplayValues();
var data = dataRange.getValues();
for (i in data) {
var row = data[i];
var emailAddress = row[2]; // Third column
var subject = 'Request';
var body = "Dear general partner,"
var file = DriveApp.getFileById('xxxxx');
var copy = row[5]; // Sixth column
GmailApp.sendEmail(emailAddress, subject, body, {cc: copy, attachments: 
[file]});
} 
}

这段代码是上述代码,一直循环直到到达空白行。

1 个答案:

答案 0 :(得分:0)

尝试一下:

function sendEmails() {
  var sh=SpreadsheetApp.getActiveSheet();
  var data=sh.getRange(2,1,sh.getLastRow()-1,6).getValues();
  //var qdate=sh.getRange("D2").getDisplayValue(); //not used
  //var ddate=sh.getRange("E2").getDisplayValue(); //not used
  var file = DriveApp.getFileById('xxxxx');
  var subject = 'Request';
  var body = "Dear general partner," 
  for (var i=0;i<data.length;i++) {
    if(data[i][2] && data[i][5]) {//if email or copy are undefined just skip
      var emailAddress = data[i][2]; // Third column
      var copy = data[i][5]; // Sixth column
      GmailApp.sendEmail(emailAddress, subject, body, {cc: copy, attachments:[file]});
    }
  } 
}

您应该为键/值对象for (i in data) {保留这种循环的使用,并且应该始终声明i with var i=