我每天都有一个脚本。它非常缓慢,我无法弄清楚是什么在减慢速度。有人有什么建议吗?我最初编写了一个函数来做一张表,然后我添加了一个函数来循环并在每张表上调用它。
function addAllLog() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var allSheets = ss.getSheets();
// build array of all sheets
for (var i in allSheets) {
if (i == 0) { continue;} // skip first sheet
var tmpName = allSheets[i].getName();
if (tmpName == "Print Sheet") break; //stop at this tab
var tmpName = ss.getSheetByName(allSheets[i].getName());
ss.setActiveSheet(ss.getSheetByName(allSheets[i].getName()));
addLog();
}
}
function addLog () {
var sheet = SpreadsheetApp.getActiveSheet();
var numLastRow = sheet.getLastRow();
var numThisRow = numLastRow+1;
today = new Date();
today.setDate(today.getDate()-1);
today = Utilities.formatDate(today,"EDT","MM/DD/YYYY");
if (sheet.getMaxRows() == numLastRow) sheet.insertRowAfter(numLastRow);
var range = sheet.getRange(numLastRow,2,1,16); // last row, column b, 1 row of 16 columns
var data = range.getValues();
range.copyTo(sheet.getRange(numLastRow+1, 2,1,16)); //you will need to define the size of the copied data see getRange()
sheet.getRange(numThisRow, 1).setValue(today);
sheet.getRange(numThisRow, 4).setValue('Log');
sheet.getRange(numThisRow, 5).setValue(''); //erase copied value if there was anything there
sheet.getRange(numThisRow, 7).setValue(''); //erase copied value if there was anything there
sheet.getRange(numThisRow, 6).setValue('=GoogleFinance(C' + numThisRow + ',"price")');
sheet.getRange(numThisRow, 6).setValues(sheet.getRange(numThisRow,6).getValues());
}
任何有关加快速度的建议都将不胜感激!
答案 0 :(得分:0)
此版本并不要求您激活每张纸张,因此可能需要的时间少一些。
function addAllLog() {
var ss=SpreadsheetApp.getActive();
var allSheets = ss.getSheets();
for (var i=1;i<allSheets.length;i++){
var shtname = allSheets[i].getName();
if (shtname == "Print Sheet"){
break; //stop at this tab
}else{
addLog(shtname);
}
}
}
function addLog (shtname) {
var sheet = SpreadsheetApp.getSheetByName(shtname);
var numLastRow = sheet.getLastRow();
var numThisRow = numLastRow+1;
today = new Date();
today.setDate(today.getDate()-1);
today = Utilities.formatDate(today,"EDT","MM/DD/YYYY");
if (sheet.getMaxRows() == numLastRow) sheet.insertRowAfter(numLastRow);
var range = sheet.getRange(numLastRow,2,1,16);
range.copyTo(sheet.getRange(numLastRow+1, 2,1,16));
sheet.getRange(numThisRow, 1).setValue(today);
sheet.getRange(numThisRow, 4).setValue('Log');
sheet.getRange(numThisRow, 5).setValue('');
sheet.getRange(numThisRow, 7).setValue('');
sheet.getRange(numThisRow, 6).setFormula('=GoogleFinance(C' + numThisRow + ',"price")');
}
答案 1 :(得分:0)
每次在电子表格上直接设置一个范围内的值时,至少需要800毫秒才能完成,因此,解决此问题的最佳方法是使用值创建一个Object[][]
并使用{ {1}},请确保sheet.getRange(range).setValues(Object[][])
的宽度高度与Object[][]
相同。
在本文Best Practices | Apps Script中,Google解释了不同之处。
另外,一个有趣的解决方案是制作一个Spreadsheet abstraction in memory。我根据这种方法制作了自己的MemsheetApp,效果很好。如果您要改进请求,我会收到请求。