0
我有一個循環通過數組C:D在A:B中找到匹配的函數,如果有它用D替換B中的值,並且如果沒有匹配它追加C:D到A:B。這個函數使用循環。我知道有一種方法來優化這個,但我迷路了。如果沒有循環,該腳本如何運行?優化谷歌應用程序腳本替換/附加值
function moveValues() {
var ss = SpreadsheetApp.openById('open_id');
var source = ss.getRange('sheet2!D:C');
var destination = ss.getRange('sheet2!A:B');
var destCount = 0;
for (var j = 1; j <= destination.getLastRow(); j++) {
if (destination.getCell(j,1).getValue() == "") {
destCount = j;
break;
}
}
for (var i = 1; i <= source.getLastRow(); i++) {
Logger.log(source.getLastRow());
var added = false;
var targetName = source.getCell(i,1).getValue();
var copyValue = source.getCell(i,2).getValue();
if (targetName == "") {
break;
}
for (var j = 1; j <= destCount; j++) {
var curName = destination.getCell(j,1).getValue();
if (copyValue != "" && targetName == curName) {
destination.getCell(j, 2).setValue(copyValue);
added = true;
break;
}
}
if (!added) {
destination.getCell(destCount, 1).setValue(targetName);
destination.getCell(destCount, 2).setValue(copyValue);
destCount += 1;
}
}
source.clear();
};
每個getCell api調用都需要時間,所以使用.getValues()只需要一次,它會返回一個包含範圍值的二維數組,這會更快。還要在一個範圍內使用.setValues(newValues)設置新值,最後只能調用一個api。 –