google-apps-script - 是否可以在事件工作表更改时触发事件?

标签 google-apps-script google-sheets

当 Google 表格中的事件工作表发生变化时,是否会触发一个事件?每次 getActiveSheet() 的结果发生变化时,我都想调用一个函数来更新侧边栏中的一些值,我为帮助在特别大的 Google 表格电子表格中导航而构建的侧边栏。

最佳答案

您可以使用 onSelectionChange()简单的触发器。只要选择了新单元格,它就会触发,包括事件工作表更改时。 (这是 introduced April 22, 2020 ,在最初的问题被问到之后。)

The onSelectionChange(e) trigger runs automatically when a user changes the selection in a spreadsheet. Most onSelectionChange(e) triggers use the information in the event object to respond appropriately.

字符串化的事件对象如下所示:

{
  "authMode": {},
  "range": {
    "rowEnd": 1,
    "columnStart": 1,
    "rowStart": 1,
    "columnEnd": 1
  },
  "source": {}, // Represents the spreadsheet itself
  "user": {
    "nickname": "NICKNAME",
    "email": "EMAIL"
  }
}

这将在事件工作表更改时显示一个消息框,第一次运行时除外。它还尝试将对 PropertiesService 的调用最小化为 quota exists在上面。请注意,它使用工作表 ID,因为它们是不可变的,这与工作表名称不同。

function onSelectionChange(e) {
  if (activeSheetChanged(e.range.getSheet().getSheetId())) {
      Browser.msgBox(e.range.getSheet().getName());
  }
}

/**
 * Check if the active sheet changed.
 * Will give a false positive if no value exists in the properties.
 * @returns {boolean}
 */
function activeSheetChanged(newSheetId) {
  const key = 'activeSheetId';
  const cache = CacheService.getUserCache();
  let properties;
  const savedSheetId = getSavedSheetId();
  if (savedSheetId != newSheetId) {
    saveSheetId(newSheetId);
    return true;
  }
  return false;
  
  /**
   * Get the saved sheet ID from the Cache/Properties.
   * @returns {Number}
   */
  function getSavedSheetId() {
    let savedSheetId = cache.get(key);
    if (savedSheetId == null) {
      properties = getProperties();
      savedSheetId = properties.getProperty(key);
      cache.put(key, savedSheetId);
    }
    return cache.get(key);
  }
  
  /**
   * Save the sheet ID to the Cache & Properties
   */
  function saveSheetId(sheetId) {
    properties = properties ? properties : getProperties();
    properties.setProperty(key, sheetId);
    cache.put(key, sheetId);
  }
  
  /**
   * @returns {PropertiesService.Properties}
   */
  function getProperties() {
    return PropertiesService.getUserProperties();
  }
}

关于google-apps-script - 是否可以在事件工作表更改时触发事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31484569/

相关文章:

google-apps-script - 如何找到我的 Google 日历事件的事件 ID?

javascript - 来自 Google Spreadsheet for Apps 脚本网站/webapp 中存储的数据的 HTML 列表 - 模板化 HTML

google-sheets - 工作表特定的 QUERY 未知错误原因

web-scraping - 使用 Google Sheets 进行网页抓取。 Importxml函数xpath修正

javascript - 从日期值中提取月份

javascript - *javascript* 将所有 for 循环值提取为不同的变量

google-apps-script - 按名称打开 Google 文档电子表格

google-apps-script - 谷歌应用脚​​本: Quoting previous message thread when replying to a Gmail message

google-sheets - 计算数组中所有值的总和大于另一个单元格中的值

javascript - 使用 Google Spreadsheet 作为 JSON 文件,使用桌面到数据表会返回错误