2

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);

1 Answer 1

3

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");
    }
  };
};
Sign up to request clarification or add additional context in comments.

1 Comment

Substring case closed! That thing had been biting at my heels for days...thank you @Sandy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.