Google-sheets – Change a working function from onOpen() to onEdit()

google sheetsgoogle-apps-script

I currently have a working function that uses the onOpen() trigger to run. I am needing to make this an on edit instead of onOpen function so that a when a change is made in my master sheet, the child sheets get updated with the new information.

I need the child sheet to run the function as soon as any data is entered into the master sheet column a. I know after reading similar questions that I need to make an event trigger, however, I am not sure how this is done. I have gone into the "resources" tab and attempted to set an onEdit trigger, but it seems like if the current spreadsheet is edited then the function will be ran. If I need it to run when the master sheet is edited, should I move the script to that sheet?

Best Answer

Yes, if you want a script to be triggered by updates to spreadsheet A, then it should be bound to that spreadsheet. It can still access the other spreadsheets by their URL or Id. For example, this function copies the cells F2:H6 of the present sheet to the cells A1:C5 of another one.

function copyStuff() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sourceSheet = ss.getSheetByName('MasterSheet1')
  var ss2 = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/...');
  var targetSheet = ss2.getSheetByName('Sheet1');
  targetSheet.getRange("A1:C5").setValues(sourceSheet.getRange("F2:H6").getValues());
}