1. 代碼說明:我撰寫了這個應用腳本,對于每一行,將 A 列中的單元格著色為與該行的最后一個單元格相同的顏色,其中包含文本。此外,我使用 onEdit 觸發器,因此每當我編輯一行時,腳本都會運行。當我有大約 20 行和 20 列(2-3 秒)時,這一切正常。
2. 問題:我現在有一張大約200 行20 列的作業表,而且代碼非常慢(3-4 分鐘或更長時間)。
3. 問題:如何讓它運行得更快,或者,根據我的需要,我應該用另一種方式撰寫這個任務嗎?
4.我想過但不喜歡的解決方案:
- 將我的作業表分成幾張(對我的用例沒有幫助)
- 僅在我進行編輯時添加一個按鈕以運行應用程式(不如 onEdit 好)
5. 代碼:
function colorFirstCell() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('courseX');
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn();
var columnFirstCells = 1; // column of cell to be colored
var dataRange = sheet.getRange(1,1, lastRow, lastColumn 1).getValues();
for(var i = 0; i < lastRow; i )
{
for(var j = 0; j < lastColumn; j ) {
if(dataRange[i][j] != '' && dataRange[i][j 1] == '') { // cell not empty and cell to the right is empty
var backgroundColor = sheet.getRange(i 1, j 1).getBackground(); // get color
sheet.getRange(i 1, columnFirstCells).setBackground(backgroundColor); // set color
of first col cell
}
}
}
}
uj5u.com熱心網友回復:
我相信你的目標如下。
- 您想降低腳本的處理成本。
在這種情況下,如何進行以下修改?
修改后的腳本:
function colorFirstCell2() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('courseX');
var range = sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn());
var backgrounds = range.getBackgrounds();
var colors = range.getDisplayValues().map((r, i) => {
for (var j = r.length - 1; j >= 0; j--) {
if (r[j] != "") {
return [backgrounds[i][j]];
}
}
return [null];
});
sheet.getRange(1, 1, colors.length).setBackgrounds(colors);
}
- 在這種情況下,首先,從資料范圍中檢索值和背景顏色。然后,創建一個包含背景顏色的陣列。并且,將創建的陣列放入“A”列。
參考:
- 地圖()
- 設定背景(顏色)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/444223.html
上一篇:更新Google表單選擇資訊
下一篇:多行文本輸入的標簽損壞?
