Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I clear a column in Google Sheets using Google Apps Script?

Let's say I want to clear all values found in the column range G2:GX where GX corresponds to the last cell that is not empty.

like image 379
orschiro Avatar asked Aug 08 '17 08:08

orschiro


People also ask

How do you delete a column in a Google spreadsheet script?

Always double-check this. var data = sheet. deleteColumn(col); You'll see that deleteColumn() returns a Sheet - the same sheet you already had.

How do I clear cells in a Google spreadsheet script?

Click on Insert on your spreadsheet, and then select Drawing. From the Drawing screen, you'll add a shape for the button with a text box over the shape to put "clear", "reset", or whatever you'd like the button to say.

How do I delete a range of cells in Google script?

To clear cells of their value and/or format, use range_clear() . To delete an entire (work)sheet, use sheet_delete() . To change the dimensions of a (work)sheet, use sheet_resize() .


2 Answers

Take a look at Range.clear() method:

function clearColumn(colNumber, startRow){
  //colNumber is the numeric value of the colum
  //startRow is the number of the starting row

  var sheet = SpreadsheetApp.getActiveSheet();
  var numRows = sheet.getLastRow() - startRow + 1; // The number of row to clear
  var range = sheet.getRange(startRow, colNumber, numRows);
  range.clear();

}

or if you want to keep the A1 notation:

function clearColumnA1Notation(a1Notation){
  //a1Notation is the A1 notation of the  first element of the column

  var sheet = SpreadsheetApp.getActiveSheet();
  var firstCell = sheet.getRange(a1Notation);
  var numRows = sheet.getLastRow() - firstCell.getRow() + 1;
  var range = sheet.getRange(firstCell.getRow(), firstCell.getColumn(), numRows);
  range.clear();

}

For your example, you can use:

clearColumn(7, 2); 

or

clearColumnA1Notation("G2");
like image 69
Pierre-Marie Richard Avatar answered Nov 15 '22 09:11

Pierre-Marie Richard


sheet.getRange("G1:G").clear();

This syntax will clear a column from G1 to last available G Column value. if you want to clear it from between like from 3rd row, then you can use

sheet.getRange("G3:G").clear();

like image 31
shabnam bharmal Avatar answered Nov 15 '22 09:11

shabnam bharmal