Home > front end >  OnEdit function doesn't get range
OnEdit function doesn't get range

Time:02-15

I am a beginner to AppScript. I am developing a code for OnEdit where if A1 cell is true, delete B2 content. I don't know how to make it work.

function onEdit(e) {
  if (e.range.getA1Notation() != "A1" || e.value == true) return;
  var sh = SpreadsheetApp.getActiveSpreadsheet();
  var ss = sh.getSheetName('Sheet1');
  ss.getRange ('B2').clearContent();      
  e.range.clearContent();
}

I've changed the code a bit, but it doesn't work either.

function onEdit(e) {

  var ss = sh.getSheetByName ("Sheet1");
  if (e.ss.range.getA1Notation() != "A1" || e.value == true) return;
  var sh = SpreadsheetApp.getActiveSpreadsheet();
  ss.getRange ('B2').clearContent();      
  e.range.clearContent();

}

CodePudding user response:

Try to change:

var ss = sh.getSheetName('Sheet1');

with:

var ss = sh.getSheetByName('Sheet1');

CodePudding user response:

It seems by your question your not doing what you say. Try this instead. I'm assuming the e event occurs on another sheet not "Sheet1"?

function onEdit(e) {
  if( (e.range.getA1Notation() === "A1") && (e.value == true) ) {
    var sh = SpreadsheetApp.getActiveSpreadsheet();
    var ss = sh.getSheetName('Sheet1');
    ss.getRange ('B2').clearContent();      
    e.range.clearContent();
  }
}

CodePudding user response:

The issue with your code is event in A1 might happen in another sheet. To make sure that the event only happens in Sheet1, you have the filter it by checking the parent sheet of the event range. Also in the if statement, you added return statement which makes your script not read this part of your code:

  var sh = SpreadsheetApp.getActiveSpreadsheet();
  ss.getRange ('B2').clearContent();      
  e.range.clearContent();

Your code should look like this:

function onEdit(e) {
  var range = e.range;
  var sheet = range.getSheet();
  if (range.getA1Notation() == "A1" && sheet.getName() == "Sheet1" && e.value == 'TRUE'){
    sheet.getRange ('B2').clearContent();      
    e.range.clearContent();
  }
}
  • Related