I am trying to get this function to work in Apps Script but for the life of me I cant seem to find the problem.
I have a range of cells highlighted in one column in my sheet. I want to delete all the contents from those cells - not the rows.
Here is what I have so far:
function clearGreen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getDataRange();
var bgColors = range.getBackgrounds();
for (var i=0; i<bgColors.length; i++) {
for (var j=0; j<bgColors[i].length; j++) {
if (bgColors[i][j] === '#D9E9D3') {
range.getCell(i+1,j+1).clearContent();
}
}
}
}
The error it is returning when trying to debug is as follows:
TypeError: Cannot read property 'getSheets' of null
clearGreen @ Code.gs:4
UPDATE: The below solution worked perfectly and much faster than my code. NOTE your worksheet needs to be the FIRST worksheet in your workbook, mine was sheet 59 so once I moved it to the first position it executed perfectly.
THANK YOU!
Try to change the line:
if (bgColors[i][j] === '#D9E9D3') {
with:
if (bgColors[i][j].toUpperCase() === '#D9E9D3') {
And it will work much faster this way:
function clearGreen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getDataRange();
var bgColors = range.getBackgrounds();
var data = range.getValues() // <--- get all the data as an array
for (var i=0; i<bgColors.length; i++) {
for (var j=0; j<bgColors[i].length; j++) {
if (bgColors[i][j].toUpperCase() === '#D9E9D3') {
data[i][j] = ''; // <--- change the array
}
}
}
range.setValues(data); // <--- put the array back on the sheet
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.