问题
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);
}
}
回答1:
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
bySpreadsheetApp.getActiveSpreadsheet()
References
- Simple Triggers - Google Apps Script Guides
- Functions - MDN JavaScript Guide
回答2:
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?
来源:https://stackoverflow.com/questions/40743876/typeerror-cannot-read-property-source-from-undefined-line-7-file-code