'Appscript to clear data, Leaving Header (first row) intact

I have a spreadsheet that I would like to create an app script function to clear data/set values from certain cells. It also needs to work up to the last row, as I will be adding many rows. I have something started but it also wipes the header row. I would like, as I say, to be able to reset a bunch of cells however many rows there are, but preserving the header.

code:

function clear() {

var header = SpreadsheetApp.getActive()
        .getRangeList(['1:1']);

var rangeList1 = SpreadsheetApp.getActive()
        .getRangeList(['I:I', 'J:J','L:L', 'N:N', 'O:O', 'P:P']);
        rangeList1.setValue("-");

var rangeList2 = SpreadsheetApp.getActive()
        .getRangeList(['C:C', 'D:D', 'G:G', 'H:H', 'M:M', 'R:R', 'S:S', 'T:T']);
        rangeList2.setValue(" ");
}

I have a function written that defines ranges based on the columns, some to be reset to '-' some to be reset to ' ' (blank)

The problem is when I run the script the correct values are placed in the correct columns, but the header is also changed. I would like to preserve or protect the header. (script also activated by menu item available in the menu bar btw)

I've tried using .offset but I can't get the syntax correct.



Solution 1:[1]

// clear values in named range - KEEPS HEADERS USED **********

function clear() {

var header = SpreadsheetApp.getActive()
        .getRangeList(['1:1']);

var rangeList1 = SpreadsheetApp.getActive()
        .getRangeList(['I2:I', 'J2:J','L2:L', 'N2:N', 'O2:O', 'P2:P']);
        rangeList1.setValue("-");

var rangeList2 = SpreadsheetApp.getActive()
        .getRangeList(['C2:C', 'D2:D', 'G2:G', 'H2:H', 'M2:M', 'R2:R', 'S2:S', 'T2:T']);
        rangeList2.setValue(" ");
}
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Solution 2:[2]

I did it

  1. getting all the data from the sheet
  2. checking how many cells exist in this sheet
  3. getting all cells from the cell just below the header to the last cell
  4. and finally, clearing all these cells.
function clear(sheet, headerSize = 0) {
  const nRows = sheet.getMaxRows();                   // number of rows on the sheet
  const nColumns = sheet.getMaxColumns();             // number of columns on the sheet
  const lastCell = sheet.getRange(nRows, nColumns);   // the last cell of this sheet

  // get the cells from the row just below the header
  //  from the first to the last column
  const data = sheet.getRange('A' + (headerSize + 1) + ':' + lastCell.getA1Notation());  

  data.clear();
}


// clear all cells leaving the header (first row) as it is
const sheet = SpreadsheetApp.getActive();
const headerSize = 1;
clear(sheet, headerSize);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matt Jackson
Solution 2 Wesley Gonçalves