Home > OS >  Using the onEdit function to only edit one tab
Using the onEdit function to only edit one tab

Time:10-26

I've seen many similar questions like this asked, but I'm still stumped.

I want an onEdit script to only work on a specific tab. I've tried several things but none of them are working correctly.

The tab on my sheet is called 'WEB Graffiti'. I want to run this script on other tabs on my sheet, but the columns are in different orders. I know how to edit the script to edit different columns but I don't know how to make it only work on the specified tab.

Here is the script I'm using.

function onEdit(e) {

  if (!e) {
    throw new Error(
    );
  }
  indirectTimestamp_(e);
}

/**
* Inserts a timestamp in column T when column B is edited
* and column C contains the value TRUE.
*
* @param {testing} e The onEdit() event object.
*/
function indirectTimestamp_(e) {
  if (e.range.columnStart !== 2
    || e.range.offset(0, 1).getDisplayValue() !== 'TRUE') {
    return;
  }
  const timestampCell = e.range.offset(0, 18);
  timestampCell.setValue(new Date()).setNumberFormat('mmm" "d" "yyyy');
};

I tried adding

  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('WEB Graffiti'), true);

I tried this and several variations in various locations of the script and it was not working properly.

CodePudding user response:

It's not clear if you want to only EDIT WEB Graffiti, or only run the procedure when that WEB Graffiti is EDITED. OnEdit will always run, the only thing you can do is scope it to make changes based on where the edit was conducted.

The below code of yours will only execute the indirect function when the WEB Graffiti sheet is edited.

function onEdit(e) {
  var myRange = e.range;
  var theSheetName = myRange.getSheet().getName();

  if (!e) {
    throw new Error(
    );
  }

  if(theSheetName == 'WEB Graffiti'){
  indirectTimestamp_(e);
  }
}

CodePudding user response:

Do this for Sheet1

function onEdit(e) {
  const sh = e.range.getSheet();
  if(sh.getName() == "Sheet1") {
    //perform rest of your code which is for sheet1
  }
}
  • Related