Google Apps Script Sheets - Functions

getSheet - Save coding space

If you have MANY different functions that need to reference the Active Sheet for various purposes, you can save a bit of typing, and use this generic function to reference the the active sheet as well as a specific tab.  This full function takes 5 lines of code (not counting the comment).  Inside the function you see 2 actual commands that you can include to set up the sheet reference. 

function getSheet() {

  // This function sets the current sheet as the active sheet for the other functions

  var ss = SpreadsheetApp.getActive();

  var active_sheet = SpreadsheetApp.setActiveSheet(ss.getSheets()[0]);

  return active_sheet;

}

So take for example our Cycle Through Cells page and function.  It could be modified to :

function stripDomain() { // placing in column B

  var active_sheet = getSheet();

  var last_row = active_sheet.getLastRow();

  var range = active_sheet.getRange("A2:A" + last_row);

  for (row = 2, len=last_row; row <= len; row++) {;

    var modEmailDomain = active_sheet.getRange("B" + row);

    var currentemail = active_sheet.getRange("A" + row).getValue();

    domainArray = currentemail.split("@");

    domain = domainArray[1]

    modEmailDomain.setValue(domain);

    //Logger.log(domainArray);

  }

}

function getSheet() {

  // This function sets the current sheet as the Active Spreadsheet for the other functions

  var ss = SpreadsheetApp.getActive();

  var active_sheet = SpreadsheetApp.setActiveSheet(ss.getSheets()[0]);

  return active_sheet;

}

If you have 3 or more functions that need to reference the sheet, it is more efficient to put it in a function, and just call the function with a single line.