FNDevCJ
FNDevCJ

Reputation: 137

Exit Google Script if cell already populated with data

I have a script that is doing simple automation. I need to check to see if data already exists and if so, simply exit the entire function, rather than continue setting values. How do I do that with this script? Thanks!

function onEdit() {
  var sheetName = "SUPPORT INFO";
  var s = SpreadsheetApp.getActiveSheet();
  if (s.getName() !== sheetName) return;
  var r = s.getActiveCell();
  if( r.getColumn() != 2 ) { //checks the column
    var row = r.getRow();
    var date = new Date();
    SpreadsheetApp.getActiveSheet().getRange('B' + row.toString()).setValue(date);
    SpreadsheetApp.getActiveSheet().getRange('A' + row.toString()).setValue("Closed");
    SpreadsheetApp.getActiveSheet().getRange('O' + row.toString()).setValue("TECH1");
  };
};

Upvotes: 1

Views: 1118

Answers (1)

Alan Wells
Alan Wells

Reputation: 31300

Determine what the logic of the program flow should be. If you need the code to only work with one column, then you can exclude every thing else.

Exclude all other columns:

var theActiveRange = sheet.getActiveCell();

columnNumberToUse = X;

if ( theActiveRange.getColumn() !== columnNumberToUse) {return;}//quit if this column 
//is any column other than X

if (!theActiveRange.getValue()) {return;}

So, using this code, if you assign the variable columnNumberToUse a value of 2, then when the column number is 2 the code will continue to run. So, if the code gets past the lines:

columnNumberToUse = 2;

if ( theActiveRange.getColumn() !== columnNumberToUse) {return;}//quit if this column 
//number is not equal to the columnNumberToUse

//If the code gets to here - then you know the active range is column 2

You need to understand the "not" operator, which is an exclamation point.

var is_it_true = 1 !== 5;

The number 1 is not equal to 5, so the above line of code will have a value of true for the variable is_it_true

The example code is testing for whether the column number is not equal to 2.

Upvotes: 1

Related Questions