Google 电子表格行更新问题及其答案是指“旧表格”,其行为与 2015 版 Google 表格不同。“新工作表”不会自动刷新内容;现在仅评估更改以响应编辑。
虽然 Sheets 本身不再提供此功能,但我们可以使用脚本来刷新“导入”公式(、IMPORTXML
和IMPORTDATA
)。IMPORTHTML
IMPORTANGE
实用程序脚本
对于IMPORT公式的定期刷新,将此函数设置为时间驱动触发器。
注意事项:
- 其他脚本或用户在刷新期间对电子表格所做的导入函数公式更改可能会被覆盖。
- 重叠刷新可能会使您的电子表格不稳定。为了缓解这种情况,实用程序脚本使用
ScriptLock
. 这可能与脚本中该锁的其他用途发生冲突。
/**
* Go through all sheets in a spreadsheet, identify and remove all spreadsheet
* import functions, then replace them a while later. This causes a "refresh"
* of the "import" functions. For periodic refresh of these formulas, set this
* function up as a time-based trigger.
*
* Caution: Formula changes made to the spreadsheet by other scripts or users
* during the refresh period COULD BE OVERWRITTEN.
*
* From: https://stackoverflow.com/a/33875957/1677912
*/
function RefreshImports() {
var lock = LockService.getScriptLock();
if (!lock.tryLock(5000)) return; // Wait up to 5s for previous refresh to end.
// At this point, we are holding the lock.
var id = "YOUR-SHEET-ID";
var ss = SpreadsheetApp.openById(id);
var sheets = ss.getSheets();
for (var sheetNum=0; sheetNum<sheets.length; sheetNum++) {
var sheet = sheets[sheetNum];
var dataRange = sheet.getDataRange();
var formulas = dataRange.getFormulas();
var tempFormulas = [];
for (var row=0; row<formulas.length; row++) {
for (col=0; col<formulas[0].length; col++) {
// Blank all formulas containing any "import" function
// See https://regex101.com/r/bE7fJ6/2
var re = /.*[^a-z0-9]import(?:xml|data|feed|html|range)\(.*/gi;
if (formulas[row][col].search(re) !== -1 ) {
tempFormulas.push({row:row+1,
col:col+1,
formula:formulas[row][col]});
sheet.getRange(row+1, col+1).setFormula("");
}
}
}
// After a pause, replace the import functions
Utilities.sleep(5000);
for (var i=0; i<tempFormulas.length; i++) {
var cell = tempFormulas[i];
sheet.getRange( cell.row, cell.col ).setFormula(cell.formula)
}
// Done refresh; release the lock.
lock.releaseLock();
}
}