问题描述
我有一个函数可能需要一段时间才能返回输出。有没有办法让它在单元格中打印一条消息,然后在短时间内用输出覆盖消息?该函数可能需要 30 秒才能运行,它可能会在 20-30 个单元格中使用,因此很高兴看到哪个单元格仍在计算,哪些已完成。
function do_calc() {
print("Now doing the calculations...")
// ... (bunch of code here that does the calculations)
return output;
}
我尝试使用 setvalue() 但它说我无权在自定义函数中这样做。
更新:添加图片 screenshot
function myFunction() {
var sheet = SpreadsheetApp.getActiveSheet();
var active_range = sheet.getActiveRange();
sheet.getRange(active_range.getRowIndex(),10).setValue('Running...');
Utilities.sleep(10000);
return 'Finished';
}
解决方法
问题:
就像我在评论中所说的那样,您不能 return
两次,因为第一个 return
语句会取消后面的代码。
- 在自定义函数中也不允许设置方法(如
setValue
),如 official documentation 中明确所述。
解决方案:
解决方案是合并内置的 Google 表格公式 IFERROR。
=iferror(myFunction(),"Running...")
其中 myFunction
是:
function myFunction() {
try{
// some code that delays
Utilities.sleep(10000);
}
catch(e){
return e.message;
}
return 'Finished';
}
我添加了 try...catch 以确保您 return
与脚本相关的错误消息。否则,iferror
将隐藏它们。
小心!
自定义函数调用必须在 30 秒内返回。如果超过这个时间,则自定义函数将返回错误:
超过最大执行时间
这将不会显示,因为您使用了 iferror
将覆盖错误。