Home > Net >  How do you activate a cell by referencing the row and column of another cell?
How do you activate a cell by referencing the row and column of another cell?

Time:06-29

In the for-loop of the onEdit function, I am attempting to activate a cell by referencing the location of another cell. This is done to allow the function to activate the cell directly to the right of the currently active cell, no matter which cell between D2 and D27 is currently active. The endgame here is to be able to enter a part number into column D, then have the cell directly to the right activate so a quantity can be entered.

var ss = SpreadsheetApp.getActive()
var sheet1 = SpreadsheetApp.getActive().getSheetByName("Sheet1")
function selectedRange()  {
  return sheet1.getA1Notation();
}
//Set active cell to A2 (cell below Name header) when file is opened.
function onOpen() {
  sheet1.getRange('A2').activate();
}
//Look for name from scanner
function onEdit(e) {
  var range = e.range;
  if (range.getA1Notation() === 'A2') {
    var active = ['Alpha', 'Beta'].includes(range.getValue()) ? "D2" : "A2";  //D7 for 
    correct responses, A2 for incorrect (repeats the process)
    sheet1.getRange(active).activate();
  }
//Does this cell contain a valid part number?
  var values = sheet1.getRange('D2:D27').getValues();
  for(var i in values){
    if(values[i][0].match("PLA-OPTRET1-")!=null){ //Retainer Element 1
      //cell contains "PLA-OPTRET1-". Do something
      //sheet1.getRange('B2').activate();
      range.offset(0,1);
      break;
    } 
    
    if(values[i][0].match("PLA-OPT1-")!=null){  //Element 1
     //cell contains "PLA-OPT1-". Do something 
     sheet1.getRange('B2').activate();
     break;
    }    
    }
}

When I run the code and meet the criteria to trigger the case with the offset, nothing happens. I don't get any errors - the cell that I just wrote my product number into remains highlighted.

I know the event is triggering because I have tried activating a cell with an absolute reference using A1 notation, but this will not work for my uses.

CodePudding user response:

You can do it using range.offset(row, column).

range.offset(0,1);

To activate,

range.offset(0,1).activate();
  • Related