Vin
Vin

Reputation: 2155

Script gives error when spreadsheet range doesn't exist

I have this simple line of code in my Google Apps Script:

  s.getRange('C2:C').clearContent();  

but sometimes my spreadsheet only has one row, so C1 is there but C2:C does not exist. In such case, the script gives an error.

Does anyone know how I can achieve the same function as the above code but so that there is no error when only Row 1 exists?

I have this so far, but I don't know if there's anything wrong with it. It seems too simple:

function Test() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getSheetByName('Sheet1');
  var values = s.getRange('C:C');
  var howManyRows = values.getNumRows();

    if (howManyRows >= 2)
       s.getRange('C2:C').clearContent();
    }
}

Upvotes: 0

Views: 1121

Answers (1)

Serge insas
Serge insas

Reputation: 46794

the method getMaxRows() returns the number of available rows in a sheet, so you could use it in a condition like this :

if(s.getMaxRows()>1){s.getRange('C2:C').clearContent()}

Upvotes: 1

Related Questions