简体   繁体   中英

Google Apps Script .getMonth isn't working if there is no available “return”

I'm trying to use "get.Month" but when I run the code there's an error:

"TypeError: exSheet.getRange (...). GetValue (...). GetMonth is not a function"

When I put the "return tempSum;" outside the "if" No error and code works...

I tried putting ".setValue" instead of "return" and it didn't help.

Does anyone know how to fix it?

function CALC_EX(chosenMonth){

  switch(chosenMonth){
  case "jan":
    chosenMonth = 1;
    break;
  case "feb":
    chosenMonth = 2;
    break;
  case "mar":
    chosenMonth = 3;
    break;
  case "apr":
    chosenMonth = 4;
    break;
  case "may":
    chosenMonth = 5;
    break;
  case "jun":
    chosenMonth = 6;
    break;
  case "jul":
    chosenMonth = 7;
    break;
  case "aug":
    chosenMonth = 8;
    break;
  case "sep":
    chosenMonth = 9;
    break;
  case "oct":
    chosenMonth = 10;
    break;
  case "nov":
    chosenMonth = 11;
    break;
  case "dec":
    chosenMonth = 12;
  }

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var exSheet = ss.getSheetByName('Expenses');
  var tempSum = 0;

  for(var i=2;i>0;i++){
    var range = exSheet.getRange(i, 5);
    var monthCell = exSheet.getRange(i, 5).getValue().getMonth()+1;

    if(!range.getValue()){
      i = 0;
      return tempSum;
    }
    if(monthCell === chosenMonth){
      tempSum = tempSum + exSheet.getRange(i, 12).getValue();
    }
  }
}

getMonth() is a Javascript function that can only be applied to a date object

TypeError: SpreadsheetApp.getActiveSheet(...).getRange(...).getValue(...).getMonth is not a function

means that your cell value is not recognized correctly as a date object, you can verify it with Logger.log(typeof exSheet.getRange(i, 5).getValue());

Verify that the cells you are iterating through are dates indeed (not strings or empty cells) and if necessary, set the data type to a date, eg by going from the Google Sheets UI to Format->Number->Date . Depending on your Locale settings, you might have to adjust your date format.

Without seeing your spreadsheet, most likely the reason for the error comes from your loop definition, as pointed out by theMaster.

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