简体   繁体   中英

How to access 2nd tab on Google Sheets using App Script/JavaScript?

I want to access simply the 2nd tab to get email and name values to be used to send automated emails. Currently, the code is using the first tab. Additionally, how do I specify that it should take only rows (on the second tab) which have values instead of taking the entire column with many blanks which then throw errors?

function sendemail() {
  var spreadSheet = SpreadsheetApp.getActiveSheet();
  var dataRange = spreadSheet.getDataRange();
  var data = dataRange.getValues();

  for (var i = 1; i < data.length; i++) { 
    (function(val) {
      var row = data[i];
      var emailAddress = row[1]; //position of email header — 1
      var message = 'Hi There!';
      var subject = 'Test';
      MailApp.sendEmail(emailAddress, subject, message);
      })(i);
   }
}

To get the second sheet / tab in a Spreadsheet you can use the getSheets method and take the second element of the returned list of Sheets :

var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var secondSheet = sheets[1];

To retrieve only populated rows use the getDataRange method to retrieve the Range in which data is present, and retrive the values.

var range = secondSheet.getDataRange();
var values = range.getValues();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM