Search code examples
google-apps-scriptcheckboxcount

Count # of checkboxes as part of a function within Google Apps Script?


I am trying to integrate a count of checkboxes into the following MailApp.sendEmail function to display the number of checkboxes against a certain quota. The checkboxes to be counted are in Column A. I would appreciate any guidance to count the checkboxes within the MailApp.sendEmail function or as a separate function but retrievable. I find this challenging in apps script.

var quotaLeft = getRemainingDailyQuota();
Logger.log(quotaLeft);

if(countOfCheckboxes > quotaLeft){
Browser.msgBox("You have " + quotaLeft + " and you're trying to send " + countOfCheckboxes + " emails.       Emails were not sent.);
}

This is the stand-alone function to count checkboxes but is there a way to do it within the above function?

function countOfCheckboxes(){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SHEET_NAME');
  var range = sheet.getRange("a:a");
  var values = range.getValues();
  var count = 0;
  
  for (var i = 0; i < values.length; i++) {
    if (values[i][0] === true) {
      count++;
    }
  }
  return count;
}
//Logger.log(count)

Solution

  • You can combine the snippets that you provided like this:

    function countOfCheckboxes() {
      var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SHEET_NAME');
      var range = sheet.getRange("a:a");
      var values = range.getValues();
      var quotaLeft = getRemainingDailyQuota();
      var count = 0;
    
      for (var i = 0; i < values.length; i++) {
        if (values[i][0] === true) {
          count++;
        }
      }
    
      if (count > quotaLeft) {
        Browser.msgBox("You have " + quotaLeft + " and you're trying to send " + count + " emails. Emails were not sent.");
        return;
      }
      var emailAddress = "[email protected]";
      var subject = "Your Subject";
      var body = "Your Body";
      GmailApp.sendEmail(emailAddress, subject, body);
    }
    

    I'm assuming that getRemainingDailyQuota() is already working because you did not include its snippet in the question. I just put a random number in for testing.

    This is what I get when the quota is not enough:

    https://i.sstatic.net/GvDfk.png

    This is what I get when the email is sent:

    https://i.sstatic.net/tclbl.jpg