MinneapolisCoder9
MinneapolisCoder9

Reputation: 701

Random substring error? "TypeError: Cannot find function substring in object..."

The error is:

TypeError: Cannot find function substring in object

The code loops through 10 values, checking for the first character being a number.

function TypeErrorMystery() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getActiveSheet();

  //loop from cell 1-10
  for (var i = 0; i < 10; i++) {
    var range = s.getRange(i + 1, 1)
    var substring1 = range.getValue().substring(0, 1);
      //if first character in cell is #
      if (substring1 === "#" ) {
         //write over it with "success"
         range.setValue("success");
      }
   };
}

The exact error is:

TypeError: Cannot find function substring in object 3. (line 9, file "Code"),

where line 9 is:

var substring1 = range.getValue().substring(0, 1);

Upvotes: 2

Views: 4892

Answers (1)

Alan Wells
Alan Wells

Reputation: 31320

The value in the cell is the number 3. The substring() method throws an error when being applied to a number. You should check the type of value that is returned.

if (typeof thisCellValue === 'number') {continue;};//Skip over numbers

Entire Code:

function TypeErrorMystery() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getActiveSheet();
  var range,
      substring1,
      thisCellValue;

  //loop from cell 1-10
  for (var i = 0; i < 10; i++) {
    range = s.getRange(i + 1, 1)
    thisCellValue = range.getValue();
    Logger.log('typeof thisCellValue: ' + typeof thisCellValue);

    if (typeof thisCellValue === 'number') {continue;};

    substring1 = thisCellValue.substring(0, 1);

    //if first character in cell is #
    if (substring1 === "#" ) {
      //write over it with "success"
      range.setValue("success");
    }
  };
};

Upvotes: 3

Related Questions