Google Apps Scripts onEdit trigger for specific sheets in a spreadsheet?

微笑、不失礼 提交于 2019-12-24 20:03:02

问题


I'm having trouble with finding good resources on how to setup onEdit triggers. I have a function that I only want to run when specific sheets are edited. For example say I have Sheet1, Sheet2, Sheet3, Sheet4, Sheet5. My script pulls data from sheets 2, 3, 4 and populates sheet 1. I only want my script ran when someone edits sheets 2, 3, or 4. How would I setup this trigger?


回答1:


There are multiple ways to accomplish this, each having its own merits. Do you have specific setup for each case? Do you run different functions for each case? etc.

  • Use an if statement to check the name for each sheet
    • if (name === "name 2" || name === "name 3" || ...) { /* common code */ ...
  • Use a switch statement with case fall-through (or no fall through, allowing specific setup based on the sheet)
    • switch (name) { case "name 2": ...
  • Use an array to hold the desired "valid" sheet names, and check if the edited sheet name is in the array with .indexOf()
    • var names = ["sheet 2 name", "sheet 3 name" ... ]; if (names.indexOf(name) { ...
  • and more

In all cases, you will want to grab the edited sheet's name from the event object:

// My simple-trigger function that runs on edit:
function onEdit(eventObject) {
  if (!eventObject) {
    /* the function was run from the script editor */
    return;
  }
  var editedSheetName = eventObject.range.getSheet().getName();
  /* perform some sort of comparison to figure out if 'editedSheetName'
     is one we want to work on, and if so, do so. */
  ...

You should review a Javascript language reference (such as the one on Mozilla Developer Network) to become familiar with execution flow control.

You can review what properties are available in the event object in the Apps Script trigger documentation: https://developers.google.com/apps-script/guides/triggers/events



来源:https://stackoverflow.com/questions/49465608/google-apps-scripts-onedit-trigger-for-specific-sheets-in-a-spreadsheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!