orschiro
orschiro

Reputation: 21725

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.

Upvotes: 7

Views: 18558

Answers (2)

shabnam bharmal
shabnam bharmal

Reputation: 584

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();

Upvotes: 5

Pierre-Marie Richard
Pierre-Marie Richard

Reputation: 2004

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");

Upvotes: 10

Related Questions