[英]How to make for loop script more efficient?
一般來說,我對腳本編寫非常陌生,尤其是在GAS中,並且想確保自己養成良好的習慣。 我寫了一個for循環腳本,實質上,它執行以下操作:
例如
單元格A1包含“某些內容”。 單元格B1包含“令人興奮”
單元格A2包含“新建”。 單元格B2包含“ X”
單元格A3包含“新建”。 單元格B3包含“ Y”
由於A3具有與單元格A2相同的值(該值為“ New”),因此清除了單元格B3(當前值為“ Y”),因此單元格B3中沒有值。
運行時間似乎很長,我確信這是由於我是新手編寫的,所以我想使此腳本盡可能高效。
你們中的任何腳本專家有什么建議可以提高此腳本的效率嗎?
我也希望對為什么任何建議對我自己的理解更有效率的解釋,以便以后碰巧找到此帖子的任何人也能理解。
這是腳本:
function testCode() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Test 1");
var source = sheet.getRange("A2:A");
for (i = 2; i < source.getLastRow(); i++) {
var currentCell = sheet.getRange(i,1).getValue();
var cellAbove = sheet.getRange(i-1,1).getValue();
var cellRight = sheet.getRange(i,2);
if (currentCell == cellAbove){
cellRight.clearContent(),({contentsOnly:true});
}
}
}
謝謝
最大的問題是,您在每個循環中都會獲得三個新范圍。 有一種方法可以在不獲取新范圍的情況下執行此操作。 您需要同時在A和B列中獲取數據。
function testCode() {
var cellAbove,currentCell,cellRight,data,lastRow,L,sheet,source,ss;
ss = SpreadsheetApp.getActiveSpreadsheet();
sheet = ss.getSheetByName("Test 1");
lastRow = sheet.getLastRow();
source = sheet.getRange(2,1,lastRow-1,2);//Get data starting in row 2 and column 1
//Get the number of rows that are the lastRow minus the number of rows not included
//at the top - get 2 columns
data = source.getValues();//Get a 2D array of values
L = data.length;//Get the number of elements in the outer array- which is the number of
//rows in the array
for (var i = 0; i < L; i++) {
if (i == 0) {continue;} //If this is the first loop there is no value above it to check
currentCell = data[i][0];
cellAbove = data[i-1][0];
if (currentCell == cellAbove){
cellRight = sheet.getRange(i+1,2);
cellRight.clearContent(),({contentsOnly:true});
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.