当 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/