e7ernal
e7ernal

Reputation: 1

Google Sheets - script to clear contents on isolated sheets

IM trying to get a clearcontent function to work on different tabs. Ive tried several things.

here is exactly what I want to achieve.

clear all content on defined cells within a specific tab. I want this function to work on more than 1 tab but only want the content cleared from 1 tab not all.

attempt #1.

function ClearCells() { var sheet = SpreadsheetApp.getActive().getSheetByName('tester'); sheet.getRangeList(['A6:B21' , 'D6:e13']).clearContent();}

I attached this script to a button and it works as it should but only for the specific tab named "tester". I want it to work on a variety of different pages i.e tester, tester 2, tester 3, etc

I also tried this method.

Attempt #2

function onOpen() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var menubuttons = [ {name: "Clear Sheet", functionName: "clear"},] ss.addMenu("Clear Sheet", (menubuttons)) ; } function clear() { var sheet = SpreadsheetApp.getActive().getSheetByName('tester');
sheet.getRange('A6:a21').clearContent(); }

This method works however it only works for 1 tab.

Attempts #3

function onOpen() { SpreadsheetApp.getUi() .createMenu('Reset sheet') .addItem('clearAll', 'clear') .addToUi(); }

function clear() { [{ sheetName: "tester", range: "A5:A30" }, { sheetName: "tester2", range: "A5:A30" }].map(obj => clearTable(obj)) }

function clearTable(obj) { SpreadsheetApp.getActive().getSheetByName(obj.sheetName).getRange(obj.range) .clearContent(); }

Ideally, id like to put a button on each tab and that button would reset the content on a defined rangelist on that specific tab only

Upvotes: 0

Views: 1082

Answers (1)

Tanaike
Tanaike

Reputation: 201643

From Ideally, id like to put a button on each tab and that button would reset the content on a defined rangelist on that specific tab only,

In this case, how about the following modified script?

Modified script:

function ClearCells() {
  var sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRangeList(['A6:B21', 'D6:E13']).clearContent();
}
  • In this modified script, when you assign "ClearCells" to the button on each tab and click the button, the sheet with the button is used. And, the ranges are always 'A6:B21', 'D6:E13' on each sheet.

  • For example, if you want to clearContent() to the specific sheets by running a script, you can also use the following script. In this script, the sheets of tester, tester 2, tester 3,,, are used.

      function ClearCells2() {
        var sheets = SpreadsheetApp.getActive().getSheets();
        sheets.forEach(sheet => {
          if (/^tester/.test(sheet.getSheetName())) {
            sheet.getRangeList(['A6:B21', 'D6:E13']).clearContent();
          }
        });
      }
    

References:

Upvotes: 0

Related Questions