复制粘贴单元格到空单元格在一个特定的范围-谷歌应用程序脚本表



我很新的谷歌应用程序脚本,一直在玩,试图得到一块代码的工作。基本上,我试图复制一个单元格并将其粘贴到特定单元格范围内的下一个空白单元格中。

我让它工作了!但我想知道是否有一个更优化/更好的方式来写这作为一个学习时刻

function pastenext() {
var ss= SpreadsheetApp.getActiveSpreadsheet();
var s=ss.getSheetByName('Questions')
var r=s.getRange("C8:C17");
var up = s.getRange("E5")

if (r.getCell(1, 1).isBlank()) {
r.getCell(1, 1).setValue(up.getValue())
}
else if (r.getCell(2, 1).isBlank()) {
r.getCell(2, 1).setValue(up.getValue())
}
else if (r.getCell(3, 1).isBlank()) {
r.getCell(3, 1).setValue(up.getValue())
}   
else if (r.getCell(4, 1).isBlank()) {
r.getCell(4, 1).setValue(up.getValue())
} 
else if (r.getCell(5, 1).isBlank()) {
r.getCell(5, 1).setValue(up.getValue())
} 
else if (r.getCell(6, 1).isBlank()) {
r.getCell(6, 1).setValue(up.getValue())
} 
else if (r.getCell(7, 1).isBlank()) {
r.getCell(7, 1).setValue(up.getValue())
}   
else if (r.getCell(8, 1).isBlank()) {
r.getCell(8, 1).setValue(up.getValue())
}   
else if (r.getCell(9, 1).isBlank()) {
r.getCell(9, 1).setValue(up.getValue())
} 
else if (r.getCell(10, 1).isBlank()) {
r.getCell(10, 1).setValue(up.getValue())
}   
} 

使用loop让它更短,从这里:

if (r.getCell(1, 1).isBlank()) {
r.getCell(1, 1).setValue(up.getValue())
}
else if (r.getCell(2, 1).isBlank()) {
r.getCell(2, 1).setValue(up.getValue())
}
else if (r.getCell(3, 1).isBlank()) {
r.getCell(3, 1).setValue(up.getValue())
}   
else if (r.getCell(4, 1).isBlank()) {
r.getCell(4, 1).setValue(up.getValue())
} 
else if (r.getCell(5, 1).isBlank()) {
r.getCell(5, 1).setValue(up.getValue())
} 
else if (r.getCell(6, 1).isBlank()) {
r.getCell(6, 1).setValue(up.getValue())
} 
else if (r.getCell(7, 1).isBlank()) {
r.getCell(7, 1).setValue(up.getValue())
}   
else if (r.getCell(8, 1).isBlank()) {
r.getCell(8, 1).setValue(up.getValue())
}   
else if (r.getCell(9, 1).isBlank()) {
r.getCell(9, 1).setValue(up.getValue())
} 
else if (r.getCell(10, 1).isBlank()) {
r.getCell(10, 1).setValue(up.getValue())
}  

:

for(var i = 1; i <= 10; i++)
if (r.getCell(i, 1).isBlank()) { // If the specific cell found is blank
r.getCell(i, 1).setValue(up.getValue());
break; // exit the loop after set value
}

break的使用与之前冗长的else if相同,因此它只会找到当前数据的满足条件,然后忽略其他条件,或者在找到满足条件后跳过/忽略其他条件else if块。

最新更新