Search code examples
google-apps-scriptcell

Clear cells across two or more sheets


I have the following simple script which deletes a range of cells from one sheet. How can I amend this so that I can specify cells across more than one sheet? I assume it's something to do with changing getSheetByName? Many thanks.

function clearandover() {
  //replace 'Sheet1' with your actual sheet name
  var sheet = SpreadsheetApp.getActive().getSheetByName('Andover');
  sheet.getRange('B8:G').clearContent();
}

Solution

  • If you are just going to do one command on each sheet, it doesn't help you to define the sheet in a separate value. You can just do it like this:

    function clearandover() {
      var spreadsheet = SpreadsheetApp.getActive();
      spreadsheet.getSheetByName('Andover').getRange('B8:G').clearContent();
      spreadsheet.getSheetByName('Second sheet name').getRange('B8:G').clearContent();
      spreadsheet.getSheetByName('Third sheet name').getRange('B8:G').clearContent();
    }
    

    Of course you can change the range per sheet that needs to be cleared.