【问题标题】:Trigger onOpen with an IF statement使用 IF 语句触发 onOpen
【发布时间】:2020-10-08 09:20:10
【问题描述】:

我有一个脚本,我想在仅打开某些工作表时运行 onOpen,而不是脚本绑定到的电子表格中的其他工作表。所需的工作表都有名称“代理报告 - 'NameOfAgent'”。每个代理报告还包含某些单元格,可用于 IF 条件语句。从逻辑上讲,我想要这个:

如果活动工作表的名称包含“代理报告”-> 运行脚本 否则什么都不做

或者, IF 在活动工作表单元格 A2=="Role" -> 运行脚本 否则什么都不做

感谢您的帮助。

【问题讨论】:

  • 活动工作表onOpen 不会一直是第一张工作表吗?同时展示你迄今为止尝试过的内容
  • 它不一定总是同一张纸。使用中间函数并围绕它包装你的逻辑。
  • 已经回答的问题不会以使当前答案无效的方式进行更改,而是您应该发布一个新问题。考虑到这一点,我将恢复 OP 所做的最后一次编辑。

标签: javascript google-apps-script google-sheets


【解决方案1】:

onOpen 将在所有者或编辑者打开电子表格时执行,无论 url 参数中引用了哪个工作表,但您可以在 i 上包含 if 语句来控制满足条件时执行的操作.

/**
 * This will be executed always that the owner or an editor opens the spreadsheet
 *
 */
function onOpen(e){
  if(SpreadsheetApp.getActiveSheet().getName() === 'Agent report'){
    // This will be executen when the condition is true
    doSomething();
  } else {
    // This will be executen when the condition is false
    return; // This is actually not necessary as there isn't any statement after it.
  }
}

/**
 * Function to be called when the condition is met
 *
 */
function doSomething(){
  // do something
}

相关

【讨论】:

  • 谢谢你,鲁本。我不能使用“===”,因为“代理报告”不是一个唯一的名称,而是几个工作表名称中的一个常用短语,我试图让脚本在每次使用“代理报告”这样的工作表时执行" 被激活。
猜你喜欢
  • 2014-03-15
  • 2022-11-07
  • 2020-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-06
  • 2020-09-12
  • 1970-01-01
相关资源
最近更新 更多