4

I am having an issue in Google Sheets TypeError: Cannot read property "source" from undefined. (line 7, file "Code") When Running the following Code Please Help

function onEdit(event)
{ 
  var timezone = "GMT-5";
  var timestamp_format = "MM-dd-yyyy-hh-mm-ss"; 
  var updateColName = "Ticket#";
  var timeStampColName = "TimeComplete";
  var sheet = event.source.getSheetByName('InAndOut');


  var actRng = event.source.getActiveRange();
  var editColumn = actRng.getColumn();
  var index = actRng.getRowIndex();
  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues();
  var dateCol = headers[0].indexOf(timeStampColName);
  var updateCol = headers[0].indexOf(updateColName); updateCol = updateCol+1;
  if (dateCol > -1 && index > 1 && editColumn == updateCol) { // only timestamp if 'Last Updated' header exists, but not in the header row itself!
    var cell = sheet.getRange(index, dateCol + 1);
    var date = Utilities.formatDate(new Date(), timezone, timestamp_format);
    cell.setValue(date);
  }
}
Rubén
  • 34,714
  • 9
  • 70
  • 166
Evan
  • 41
  • 1
  • 1
  • 2

2 Answers2

5

source is a property of event that has not being assigned an object, so it was referred as unassigned. This occurs when a function like yours is ran directly from the script editor.

To run it from the script editor, first you have to assign an event object with the corresponding properties to the function argument. For details see How can I test a trigger function in GAS?

If you will be running it from the script editor, it's recommended:

  • To change the function name, as onEdit is one of the reserved function names.
  • To remove the function argument.
  • To replace event.source by SpreadsheetApp.getActiveSpreadsheet()

References

Community
  • 1
  • 1
Rubén
  • 34,714
  • 9
  • 70
  • 166
1

onEdit is a reserved function name for a simple trigger. The event for this trigger is the users' action on a sheet.

onEdit(e) runs when a user changes a value in a spreadsheet, see reference.

If you run the function from the editor, the event object from the function is undefined:

function onEdit(event) // undefined

If the user changes cells value, the trigger launches automatically and assigns a value to the event variable.

Please see this answer on How can I test a trigger function in GAS?

Max Makhrov
  • 17,309
  • 5
  • 55
  • 81
  • 1
    Actually onEdit could be ran "always". The problem is related to the event object. :) – Rubén Nov 22 '16 at 15:19
  • 1
    What I meant is that the direct problem was not the name of the function, the problem was that the argument has not a object assigned. I describe this on my answer. – Rubén Nov 22 '16 at 15:55