gpt4 book ai didi

google-apps-script - Google Apps 脚本函数 getActiveSheet() 不返回事件工作表

转载 作者:行者123 更新时间:2023-12-02 20:30:21 26 4
gpt4 key购买 nike

The Google Apps Script Developers' Guide's definition of an "active sheet" :

The active sheet in a spreadsheet is the sheet that is being displayed in the spreadsheet UI.

my sheets

如果我有三个工作表,分别命名为 Mary、Moe 和 Joe,并将 Mary 工作表保留在显示状态(因此,它是事件工作表)并运行以下简单脚本:

function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
Logger.log(sheet.getName());

ss.setActiveSheet(ss.getSheets()[2]);
Logger.log(ss.getActiveSheet().getName());
}

我希望输出是这样的

[18-10-26 18:41:45:724 EDT] Mary
[18-10-26 18:41:45:730 EDT] Joe

但是,事实上,它说:

[18-10-26 18:49:14:752 EDT] Moe
[18-10-26 18:49:14:755 EDT] Joe

如果我在不接触纸张的情况下第二次运行它,我希望输出是这样的

[18-10-26 18:50:51:930 EDT] Joe
[18-10-26 18:50:51:933 EDT] Joe

但它实际上说的是和以前一样的事情

[18-10-26 18:50:51:930 EDT] Moe
[18-10-26 18:50:51:933 EDT] Joe

换句话说,设置事件工作表确实会更改电子表格 UI 中显示的工作表,但它似乎并未在内部将新工作表注册为事件工作表。即使将事件工作表设置为不同的工作表后,GAS 始终将 Moe 识别为事件工作表。

我希望得到解释和解决此问题的方法。基本上,我只需要 getActiveSheet()getActiveRange() (有类似的问题)来为我提供当前在电子表格 UI 中可见的工作表,完全按照中的定义开发者指南。

编辑:我找到了解决此问题的方法。我引用了评论中的内容。

Hi everyone, thank you all for your input. I just discovered that getActiveSheet() does indeed work the way I was hoping it would, but only if you run the function through a custom menu UI built using SpreadsheetApp.getUi().createMenu(...), which needs an onOpen() trigger (thanks to @I'-'I for this tip). Running the function from the script editor causes the problems that inspired my original post.

然而,虽然我很高兴找到了解决方案,但感觉更像是一种解决核心问题的解决方法。我觉得在这两种情况下,在菜单 UI 和脚本编辑器中 getActiveSheet() 都应该按照开发人员指南中的定义进行操作。它在一种情况下有效而在另一种情况下不起作用,这是没有意义的。

最佳答案

显示所有工作表 10 秒

此脚本将循环浏览电子表格中的所有工作表,每次激活它们并显示它们大约 10 秒。

function cycleThroughAllSheets() {
var ss=SpreadsheetApp.getActive();
var shA=ss.getSheets();
var start=new Date();
for(var i=0;i<shA.length;i++){
shA[i].activate();
SpreadsheetApp.flush();
ss.toast('Active Sheet is ' + shA[i].getName());
do{
//nothing
}while(new Date().valueOf()-start.valueOf()<10000);
start=new Date();
}
ss.toast('End of Script.')
}

关于google-apps-script - Google Apps 脚本函数 getActiveSheet() 不返回事件工作表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53017230/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com