电子表格中特定工作表的onEdit触发器? [英] onEdit trigger for specific sheets in a spreadsheet?

查看:75
本文介绍了电子表格中特定工作表的onEdit触发器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法找到有关如何设置onEdit触发器的良好资源。我有一个仅在编辑特定图纸时才要运行的功能。例如说我有Sheet1,Sheet2,Sheet3,Sheet4,Sheet5。我的脚本从工作表2、3、4提取数据并填充工作表1。我只希望我的脚本在有人编辑工作表2、3或4时运行。

解决方案

有多种方法可以完成此操作,每种方法各有优点。您是否有针对每种情况的特定设置?您是否针对每种情况运行不同的功能?




  • 使用 if 语句检查每张纸的名称


    • 如果(name === name 2 || name === name 3 || ...){/ *通用代码* / ...


  • 使用开关带有大小写掉落的语句(或不掉落,允许基于工作表进行特定设置)


    • name){case name 2:...


  • 使用数组保存所需的有效的工作表名称,并检查已编辑的工作表名称是否在包含 .indexOf()


    • var名称= [工作表2名称,工作表3名称 ...]; if(names.indexOf(name){...


  • 及更多



在所有情况下,您都希望从事件对象中获取已编辑工作表的名称:

  //我在编辑时运行的简单触发函数:
函数onEdit(eventObject){
if(!eventObject){
/ *该函数是从脚本编辑器运行* /
return;
}
var editedSheetName = eventObject.range.getSheet()。getName();
/ *对图进行某种比较* /
...
是我们要处理的对象,如果是,请这样做。 >

您应该阅读Java语言参考(例如Mozilla Developer Network上的Java语言参考),以熟悉执行流控制。



您可以在Apps脚本触发器文档中查看事件对象中可用的属性: https://developers.google.com/apps-script/guides/triggers/events


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?

解决方案

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

这篇关于电子表格中特定工作表的onEdit触发器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆