I wanted to ask, if I can do anymore improvements regarding my runtime, currently it takes roughly 100s to finish my script(since adding the formatting script below). Before adding additional formatting, it took roughly 4-5 seconds to run all my code.
The script checks every cell in a given range, if it has a data validation linked to it and based on that to format the cell.
for(let i = 9; i < 32;i++){
for(let j = 2; j < 13; j++){
cell = sheet.getRange(i,j)
cellDataValCheck = sheet.getRange(i,j).getDataValidation()
if(cellDataValCheck != null){
cell
.setBorder(true, true, true, true, false, false, "black", SpreadsheetApp.BorderStyle.SOLID)
.setBackground("#FFFFFF")
.setHorizontalAlignment("center")
}else{
cell.setBackground("#666666")
}
}
Best Answer
Please read https://developers.google.com/apps-script/guides/support/best-practices. In summary, whenever is possible you should avoid to use Google Apps Script methods in loops as they are slow. In example, instead of making the changes one cell at a time build an Array of Arrays of the background colors, then apply all the changes at once (instead of
setBackground
usesetBackgrounds
)An option to improve the script results is to use Advances Sheets Service, more specifically batchUpdate.
Related