我有一个函数可能需要一段时间才能返回输出。有没有办法让它在单元格中打印一条消息,然后稍后用输出覆盖该消息?该函数可能需要 30 秒才能运行,并且可能在 20-30 个单元格中使用,因此很高兴看到哪个单元格仍在计算以及哪个单元格已完成。
function do_calc() {
print("Now doing the calculations...")
// ... (bunch of code here that does the calculations)
return output;
}
我尝试使用setvalue()
但它说我无权在自定义函数中执行此操作:
这是我的代码:
function myFunction() {
var sheet = SpreadsheetApp.getActiveSheet();
var active_range = sheet.getActiveRange();
sheet.getRange(active_range.getRowIndex(), 10).setValue('Running...');
Utilities.sleep(10000);
return 'Finished';
}
Issues:
就像我在评论中说的,你不能return
两次,因为第一次return
语句将取消后面的代码。
- 还设置方法(如
setValue
) 不允许出现在自定义函数中,如官方文档 https://developers.google.com/apps-script/guides/sheets/functions.
解决方案:
解决方案是合并内置的谷歌表格公式IFERROR https://support.google.com/docs/answer/3093304?hl=en.
=iferror(myFunction(),"Running...")
where myFunction
is:
function myFunction() {
try{
// some code that delays
Utilities.sleep(10000);
}
catch(e){
return e.message;
}
return 'Finished';
}
我添加了一个试着抓 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch以确保你return
与脚本相关的错误消息。否则,iferror
会隐藏它们。
当心!
自定义函数调用必须在以下时间内返回30秒。如果超过这个时间,那么自定义函数将返回错误:
超过最大执行时间
由于您已经使用过,因此不会显示iferror
这将覆盖错误。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)