首页 > 解决方案 > 使用 IF 语句触发 onOpen

问题描述

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

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

或者,如果在活动工作表单元格 A2=="Role" -> 运行脚本 ELSE 什么也不做

感谢您的任何帮助。

标签: javascriptgoogle-apps-scriptgoogle-sheets

解决方案


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

/**
 * 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
}

有关的


推荐阅读