Faheem Akhtar
Faheem Akhtar

Reputation: 113

TypeError: Cannot read property 'getRange' of null (line 14, file "Code")

I am getting this error while trying to run the email sending script in Google App script. I don't have any knowledge of Javascript(I plan to learn after learning Python) and I got this code from samples code provided by Google App script.

The number of rows and columns in Google spreadsheet: https://prnt.sc/tha2o1

Below is the code.

// This constant is written in column C for rows for which an email
// has been sent successfully.
var EMAIL_SENT = 'EMAIL_SENT';

/**
 * Sends non-duplicate emails with data from the current spreadsheet.
 */
function sendEmails2() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var startRow = 2; // First row of data to process
  var numRows = 6; // Number of rows to process
  // Fetch the range of cells A2:B3
  var dataRange = sheet.getRange(startRow, 1, numRows, 7);
  // Fetch values for each row in the Range.
  var data = dataRange.getValues();
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var emailAddress = row[0]; // First column
    var message = row[1]; // Second column
    var emailSent = row[3]; // Third column
    if (emailSent !== EMAIL_SENT) { // Prevents sending duplicates
      var subject = 'Sending emails from a Spreadsheet';
      MailApp.sendEmail(emailAddress, subject, message);
      sheet.getRange(startRow + i, 3).setValue(EMAIL_SENT);
      // Make sure the cell is updated right away in case the script is interrupted
      SpreadsheetApp.flush();
    }
  }
}

Upvotes: 0

Views: 3832

Answers (1)

Faheem Akhtar
Faheem Akhtar

Reputation: 113

I was running a standalone script and it didn't work. You are supposed to run container-bound script if you wish to work with Google Sheets/Docs/Forms/Sites. Here is how you can run the container bound script. https://developers.google.com/apps-script/guides/bound

Upvotes: 2

Related Questions