0

I am trying to simplify my google apps script code and increase its readability. To this end, instead of calling setActiveSheet() function each time I want to activate a new sheet in my code, I decided to write a function that does the job and just call that function and include the name of the sheet as an argument like this:

function setSheet (sheetName) {
  var sheetName;
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName(sheetName));
  var sheet = spreadsheet.getActiveSheet();
};

Then for example if I want to activate the sheet named "Students", I would write the following simple code:

setSheet("Students");

The above code won't work. Any help?

4
  • This has to do with local and global variables and within google-apps-script this is not as easy as usual. See this SO question Commented Jul 2, 2018 at 7:45
  • A better question is why do you need to use setActiveSheet so much that refactoring its usage even occurs to you. The only reason you need to change the active sheet is if you need to move the user's view, or the Sprreadsheet Service methods you want to use can only be called in the active sheet. For most, this is not the case. PS: it doesn't work is not a valid problem or issue description. Commented Jul 2, 2018 at 10:17
  • @tehhowch I'm just playing with the code to better grasp the logic behind. Commented Jul 4, 2018 at 5:03
  • @Casper actually it was easily done. The problem was redeclaring the same variable which reset the variable. Commented Jul 4, 2018 at 5:05

2 Answers 2

3

I did check up the above code and it works fine to me. I will attach the code snippet used.

function setSheet (sheetName) {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName(sheetName));
  var sheet = spreadsheet.getActiveSheet();
}

function myfunction(){
setSheet("Students");
}

I also noted there is an extra semi-colon used after the function is terminated which is not required.

Sign up to request clarification or add additional context in comments.

2 Comments

Read about JavaScript ASI
Thanks it works fine. My problem was that I called the same passing variable again inside the function and this resulted in resetting the variable and caused a problem.
3

Why are you declaring a variable in your function that has the same name as the function parameter that you are passing? This will reset the value that was just passed. Try removing var sheetName; from your function.

2 Comments

A common term for that is "shadow"
Thank you. This was exactly the problem of my code. Now it works fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.