google-apps-script - 谷歌表格计算延迟和相关函数调用
问题描述
这是一个使用公式填充列的函数:
function fillAccount(lastRow) {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('B1').activate();
spreadsheet.getCurrentCell().setValue(' ');
spreadsheet.getRange('B2').activate()
.setFormula('=ifna(vlookup(C2,Accounts!$A$1:$A$7,1,false),B1)');
spreadsheet.getRange('B3').activate();
var currentCell = spreadsheet.getCurrentCell();
spreadsheet.getRange('B3:B' + lastRow).activate();
spreadsheet.getRange('B2').copyTo(spreadsheet.getActiveRange(),
SpreadsheetApp.CopyPasteType.PASTE_FORMULA, false);
}
从该函数完成到 B 列中的所有行都填充有计算结果时,存在一些延迟。我想在这个函数之后执行另一个函数,但是该函数需要在执行之前填充所有行。以下是它在驱动程序脚本中的显示方式:
fillAccount(lastrow);
copyAllData(); // this needs to have all rows in column B fully
// populated.
解决方案
首先,您的函数需要进行一些清理(可以进一步完善,但这是一个开始):
function fillAccount(lastRow) {
var spreadsheet = getSpread(); //custom method calling the Spreadsheet, change to your logic;
var colB = spreadsheet.getRange('B1:B'+lastRow);
var row1 = colB.getCell(1,1);
var row2 = colB.getCell(2,1);
row1.setValue(' ');
row2.setFormula('=ifna(vlookup(C2,RENAMED!$A$1:$A$7,1,false),B1)');
row2.copyTo(colB.offset(1,0,lastRow-1), SpreadsheetApp.CopyPasteType.PASTE_FORMULA, false);
SpreadsheetApp.flush(); //make sure changes are applied;
}
然后,只需调用第二个函数并确保您访问值以确保计算(如果您有相当长的延迟(例如,每个公式计算> 1s),某些公式可能会以#ERROR!
值结束 - 如果您想考虑这一点,添加检查==='#ERROR!'
,在遇到这样的值时终止第二个函数并递归地重新启动它):
/**
* Caller function;
*/
function triggerFill() {
//...your logic and lastRow initialization here;
fillAccount(lastRow);
copyAllData();
}
/**
* Function accessing updated values;
*/
function copyAllData() {
var spreadsheet = getSpread(); //custom method calling the Spreadsheet, change to your logic;
var dataRange = spreadsheet.getDataRange(); //just an example that gets all data;
var values = dataRange.getValues(); //just an example that gets all values;
for(var i=0; i<values.length; i++) {
if(values[i].indexOf('#ERROR!')!==-1) { //for high latency;
Utilities.sleep(t) //change t to number of ms to wait to your liking;
return copyAllData();
}
}
//do other stuff, like cell copy;
}
推荐阅读
- python-3.x - TypeError: only() 接受 2 个位置参数,但给出了 3 个
- css - 从类中反应选择样式
- java - 我们如何在 Java 中的 BDD 功能文件中将 JSON 对象列表作为 JSON 字符串传递
- php - 为什么我在上传到数据库时收到 PDO 异常
- sql - 将数据从一个表复制到另一个表时使用参数或列值更好吗?
- sql - 如何使 SQL Server 中一次只有一个用户可以插入数据?
- spring-mvc - jsGrid 正在加载带有空单元格的行
- angular - 在 Angular 4 中获取响应式表单值
- python - 在使用 ctypes 测试自定义 python 包装器期间,发生“OSError:异常:访问冲突读取”
- linux - 在 CentOS 上找不到新安装的 svn 版本