Search code examples
for-loopif-statementgoogle-apps-scriptfilteringcriteria

Returning certain rows which meet a criteria - Google Apps Script


What I am trying to do is: I have a list, with N being a date and O being a checkbox. I need to get the rows which =N < Today() && O=False, then return A:B of those corresponding rows. I've tried it every which way, and I can't get it to work. Any suggestions?

function msg1(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var wscl = ss.getSheetByName('Connection List');
  var contact = wscl.getRange("A2:B").getValues();
  var msg1date = wscl.getRange("N2:N").getValues();
  var msg1sent = wscl.getRange("O2:O").getValues();
  var MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
  var now = new Date();
  var yesterday = new Date(now.getTime() - MILLIS_PER_DAY);
  for(var i=0;i<msg1sent.length;i++){
    if(msg1sent =="FALSE"&& msg1date < yesterday){ 
      var row=i+1; 
    }
  }
 } 

Solution

  • If you use getValues() of a checkbox it returns true or false booleans. If you use getDisplayValues() it returns "TRUE" or "FALSE" strings. And for the dates I just used valueOf() but you can also use getTime(). The easiest way to figure all of this out is to create some intermediate temporary variables and view them in the Script Debugger and you can see all of the return values there.

    function msg1(){
      var ss=SpreadsheetApp.getActive();
      var sh=ss.getSheetByName('Connection List');
      var ct=sh.getRange(2,1,sh.getLastRow()-1,2).getValues();
      var date=sh.getRange(2,14,sh.getLastRow()-1,1).getValues();//date
      var sent=sh.getRange(2,15,sh.getLastRow()-1,1).getValues();//checkbox
      var dt=new Date();
      var rows=[];
      var today=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();//0000 or midnight
      for(var i=0;i<sent.length;i++){
        var t1=sent[i][0];
        var t2=new Date(date[i][0]).valueOf();
        var t3=today;
        if(sent[i][0]==false && new Date(date[i][0]).valueOf()<today){ 
          rows.push(ct[i]);
        }
      }
      Logger.log(rows);
     }
    

    If you use getDisplayValues() then it would look like this:

    function msg1(){
      var ss=SpreadsheetApp.getActive();
      var sh=ss.getSheetByName('Connection List');
      var ct=sh.getRange(2,1,sh.getLastRow()-1,2).getValues();
      var date=sh.getRange(2,14,sh.getLastRow()-1,1).getValues();//date
      var sent=sh.getRange(2,15,sh.getLastRow()-1,1).getDisplayValues();//checkbox
      var dt=new Date();
      var rows=[];
      var today=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();
      for(var i=0;i<sent.length;i++){
        var t1=sent[i][0];
        var t2=new Date(date[i][0]).valueOf();
        var t3=today;
        if(sent[i][0]=="FALSE" && new Date(date[i][0]).valueOf()<today){ 
          rows.push(ct[i]);
        }
      }
      Logger.log(rows);
     }