0

I need to limit the function onEdit() to fire only when changes are made within the specific range. Users selects a value in column B and column A is opopulated with a specific value. Although the funciton below seems to work as desired, when run from within the Apps Editor, it throws an error:
TypeError: Cannot read property "source" from undefined.

which apparently refers to e.source.getSheetName line

function onEdit(e) {

  if (
    e.source.getSheetName() == "Activity" &&
    e.range.columnStart == 2 &&
    e.range.columnEnd == 2 &&
    e.range.rowStart >= 2 &&
    e.range.rowEnd <= 100
  ) {
    e.value !=='' ? e.range.offset(0,-1).setValue(caseID()) : null
    };
  };

I am not sure if this could be ignored, since the function works (inserts result of caseID function in column A, when value is changed in column B)? Thank you in advance,

AlexShevyakov
  • 425
  • 7
  • 18
  • 1
    `e` is `undefined` because there's no edit event(because there was no edit). See view> Executions for the actual error. There's also no `getSheetName()` method in spreadsheet class. The for-loop, ss, range and activity are unnecessary. – TheMaster Mar 08 '19 at 09:22
  • @TheMaster `getSheetName()` What about here: [link](https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getsheetname) – AlexShevyakov Mar 08 '19 at 09:29
  • @TheMaster Have updated the code, removed `ss, activity, range` and `for`-loop - thank you! – AlexShevyakov Mar 08 '19 at 09:40
  • 1
    Yes. It seems there's that method. But I presume that that method will only provide the first sheet's name instead of the edited sheet's name. – TheMaster Mar 08 '19 at 10:29
  • 3
    Possible duplicate of [How can I test a trigger function in GAS?](https://stackoverflow.com/questions/16089041/how-can-i-test-a-trigger-function-in-gas) – tehhowch Mar 08 '19 at 13:28

2 Answers2

1

Short answer : I guess, we can ignore that for now.

Reason : When we run that function manually in Apps Editor we don't pass the event object. So that's why it's giving e as undefined error.

I guess we can interpret running that function manually as running onEdit() whereas function signature required argument e. So that's why e is undefined when executed manually.

But when it's triggered due to edit in sheet, then that event object is passed to the function as argument and hence it works as expected.

Umair Mohammad
  • 4,489
  • 2
  • 20
  • 34
1

I believe getSheetName() only returns the first sheet's name instead of the edited sheet's name. To get the correct edited sheet name, you should first get the sheet and then it's name. Also, this is preferably done from the range rather than the source:

e.range.getSheet().getName() === "Activity"
TheMaster
  • 45,448
  • 6
  • 62
  • 85
  • Regarding this line of code: `e.value !=='' ? e.range.offset(0,-1).setValue(caseID()) : null` - how do I clear the value in column A if user delets the value in coumn B? – AlexShevyakov Mar 08 '19 at 11:20