javascriptgoogle-apps-scriptgoogle-sheets

Count cells including the date before today


I am trying to create a counter that counts the cells that include in their content the date before today as a date. However the result in cell 16,1 is always zero as it seems that my loop does not work. I know I can do it with a formula in spreadsheets but I want to use javascript. Also I am trying to find out what is wrong in MY code. I have wrirtten the following lines of code:

function job_counter() {


  var yesterday_jobs=0;
  var ss=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
  var e = new Date(new Date().getFullYear(),new Date().getMonth() , new Date().getDate())
  var yesterday = new Date(new Date().getFullYear(),new Date().getMonth() , new Date().getDate())
  yesterday.setDate(yesterday.getDate() - 1);
  var range_unformated=ss.getRange(2,3,25).getValues()
  var date;
  for (var i=1; i<25; i++){
      date=Date.parse(range_unformated[i])
      Logger.log(date[3])
      if ( date[i] - yesterday.getTime() >= 0 && date[i] != ""  ){
      yesterday_jobs = yesterday_jobs + 1 
    ss.getRange(16,2).setValue(yesterday_jobs)
    }}
    // check yesterday_jobs                       
}

Solution

  • This will solve your problem, it uses getValues getting a range of 24x24 cells and iterating it to compare every cell value to see if it is equal to yesterday:

    function isYesterday(){
      var yesterday_jobs=0;
      var ss=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      var row=0;
      var col=0;
      var date;
      var yesterday = new Date(new Date().getFullYear(),new Date().getMonth() , new Date().getDate())
      yesterday.setDate(yesterday.getDate() - 1);
    
      range = ss.getRange(1,1,25,25).getValues()
      for (var i = 0; i < 25; i++){
        for ( var j = 0; j < 25; j++) {
          date = Date.parse(range[i][j]);    
          if ( date - yesterday.getTime() <= (24 * 60 * 60 *1000)  ){
            yesterday_jobs = yesterday_jobs + 1;
          }
        }
      }
      ss.getRange(16,2).setValue(yesterday_jobs);
    }
    

    Things that were wrong...

    This is wrong and it is the reason it's not working:

          yesterday_jobs === yesterday_jobs + 1;
    

    You should be doing:

          yesterday_jobs = yesterday_jobs + 1
    

    Why?

    Because == and === are Comparison operators, and = is an assignment operator.

    What you are trying to do is to set a new value to yesterday_jobs, not to compare it, so you have to use =.

    This will solve your problems with the loop assignations.


    When doing a = 2 you are assigning a value to a variable:

    a value is now equal to 2 value


    When doing a == 2 you are asking:

    Is a equal to 2 in value?


    When doing a === 2 you are asking

    Is a equal to 2 in value and type?