Monday, November 11, 2013

A Week to Save 20 Minutes!

So, I have responded to feedback regarding my auto emailer (posted about earlier) by adding 4 lines of code that will automatically pull column headers from my spreadsheet.  First the code and then an explanation of what it does:

var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  var headers = sheet.getSheetValues(1,1,1,-1);
  var Properties = headers[0]

Since I'm new at this Javascript thing, it's highly possible that most people could accomplish the same thing with a shorter amount of code.  Also, I'm not even sure I need the first two lines.  If I understand it (doubtful), the first line gets the active sheet--my sheet, but it could be any sheet that the code is attached to, so now I can transport the code.  The second line gets the first sheet (the little tabs at the bottom of the spreadsheet, this is the difference between a "workbook" and a "sheet" in excel)--so just in case I have content on the second sheet, my script won't get confused.  The third line makes a two dimensional array object (I'm sure that's not the right term) with content starting from the 1st row, 1st column, 1 row deep, and all the way to the last column with content ( the -1 argument says "find the last column with content).  Because it's a nested array, I had to pull out the header content by setting Properties equal to the first element of the array.

In the previous version you'll notice that I had hand-written the elements in the Properties array.  What that meant was if I changed my headers on the spreadsheet--or really, the question titles on the google form that populates the spreadsheet--my script would still send an email with the original headers.  I would have to change them all by hand.  My new code makes the script pull the headers each time automatically, so if I change them between emails, it will automatically be correct on the next email.

This became necessary when my product tester requested some new data be collected with the form.  I'm too lazy to rewrite that long list of headers (I currently have like 25 on the live form!), so instead of spending 20 minutes retyping a list, I spent the better part of a week on w3schools and google script tutorials and other javascript sites learning what I needed.  "A week to save 20 minutes!" you say, but it was a week to save a 20 minutes that will with certainty be repeated.  The unknown is how often and how many times I'll have to repeat it.

My next task will be to make the same type of change for the if, then statement that currently has a "k < 12" parameter in it.  The 12 could easily turn into 13 if I change my questions again and I want the script to know when to cut off the data table in my email.