0

I have a script that I want to run onOpen when only certain sheets are open, but not others in the spreadsheet to which the script is bound. The sheets that are needed all have names "Agent report - 'NameOfAgent'". Each agent report also has certain cells inside that can be used for the IF condition statement. Logically, I want to have this:

IF name of active sheet contains "Agent report" -> run script ELSE do nothing

Alternatively, IF in active sheet cell A2=="Role" -> run script ELSE do nothing

Thank you for any help.

Rubén
  • 34,714
  • 9
  • 70
  • 166
Mike B.
  • 99
  • 3
  • 9
  • Won't the active sheet `onOpen` be always the first sheet? Also show what you've tried so far – TheMaster Oct 03 '20 at 10:33
  • 1
    It's not necessarily always the same sheet though. Use a intermediate function and wrap your logic around that. – Cooper Oct 03 '20 at 15:35
  • Questions that already were answered do not be changed in a way that it invalidates the current answers, instead you should post a new question. Considering this, I will revert the last edit made by the OP. – Rubén Oct 08 '20 at 01:19

1 Answers1

2

onOpen will be executed when the owner or the editor open the spreadsheet no matter of what sheet was referred in the url parameters but you could include an if statement on i to control what is done when the condition is met.

/**
 * This will be executed always that the owner or an editor opens the spreadsheet
 *
 */
function onOpen(e){
  if(SpreadsheetApp.getActiveSheet().getName() === 'Agent report'){
    // This will be executen when the condition is true
    doSomething();
  } else {
    // This will be executen when the condition is false
    return; // This is actually not necessary as there isn't any statement after it.
  }
}

/**
 * Function to be called when the condition is met
 *
 */
function doSomething(){
  // do something
}

Related

Rubén
  • 34,714
  • 9
  • 70
  • 166
  • Thank you, Rubén. I can't use "===" because "Agent Report" is not a unique name, but a common phrase in the names of several sheets where I'm trying to get the script executing every time such a sheet with "Agent Report" is activated. – Mike B. Oct 08 '20 at 00:36