Você está na página 1de 26

My new, free Google Sheets Course: Advanced Formulas 30 Day Challenge LEARN MORE >>

Ben Collins
Google Sheets Developer & Data Analytics Instructor. Let me help you with Google Sheets, Apps Script
and Data Studio.

Beginner guide to coding with Google Apps


Script
What is Google Apps Script or G.A.S.?

It’s a cloud based scripting language for extending the functionality of Google
Apps and building lightweight web-based applications.

What does this mean in practice: It’s a coding language where you can write small
programs performing custom behaviors that go beyond the standard features of
Google Apps. The code is stored and executed on Google’s servers.

It means you can do cool stuff like automating repetitive tasks, creating, modifying
and emailing documents to people, and linking up your Google Sheets to other
data sources. Heck, you can even build complex web forms, use a Google Sheet as
your database, programatically create charts and publish it all to the web. In other
words, you can build fully featured, lightweight web applications.
What is Google Apps Script?

Writing your first Google Apps Script

So let’s go ahead and write our first, extremely basic program, the classic “Hello
world” program beloved of computer teaching departments the world over.

In this Google Sheets script tutorial, we’re going to write a script that is bound to
our Google Sheet, or you might say contained within our Google Sheet. This is
known in the jargon as a container-bound script.

Begin by creating a new Google Sheet.

Then click the menu Tools > Script editor... to open a new tab with the code ed-
itor window.

This will open a new tab in your browser, which is the Google Apps Script editor
window:

By default, it’ll open with a single Google Script file (code.gs) and a default code
block, myFunction():

function myFunction() {

}
In the code window, between the curly braces after the function myFunction() syn-
tax, write the following line of code so you have this in your code window:

function myFunction() {
Browser.msgBox("Hello World!");
}

Your code window should now look like this:

Next hit the run button (the black triangle), which prompts you to authorize the
app to run, as shown in the following image:

Clicking Continue pops up another window in turn, showing what permissions


your app needs to run. In this instance the app wants to view and manage your
spreadsheets in Google Drive, so click Allow (otherwise your script won’t be able
to interact with your spreadsheet or do anything):

UPDATE AUGUST 2017

Google have introduced new security protections to reduce risk from unverified
apps, which affects the workflow when we first authorize our own apps.

When your first run your apps script, you may see the “app isn’t verified” screen and
warnings about whether you want to continue.

In our case, since we are the creator of the app, we know it’s safe so we do want to
continue. Furthermore, the apps script projects in this post are not intended to be
published publicly for other users, so we don’t need to submit it to Google for review
(although if you want to do that, here’s more information).

Click the “Advanced” button in the bottom left of the review permissions pop-up, and
then click the “Go to Starter Script Code (unsafe)” at the bottom of the next screen to
continue. Then type in the words “Continue” on the next screen, click Next, and final-
ly review the permissions and click “ALLOW”, as shown in this image (showing dif-
ferent script):
More information can be found in this detailed blog post from Google Developer Ex-
pert Martin Hawksey.

Next, GAS will show you two status messages to tell you what’s happening.

First this one:

And then this one:

If anything goes wrong with your code, this is stage when you’d see a warning
message (instead of the yellow message, you’ll get a red box with an error message
in it).

Now, assuming you got those two yellow status messages and they’ve both auto-
matically disappeared from view, then your program has run successfully. Click
back on the browser tab with your spreadsheet (most likely the tab to the left of
the one we’re in).

You should see the output of your program, a message box popup with the classic
“Hello world!” message:

Click on Ok to dismiss.
Great job! You’ve now written your first apps script program.

Housekeeping:

Before we continue, let’s rename our function to something more meaningful. At


present, it’s called myFunction which is the default, generic name generated by
Google. Every time I want to call this function (i.e. run it to do something) I would
write myFunction(). This isn’t very descriptive, so let’s rename it to helloWorld(),
which gives us some context.

So change your code in line 1 from this:

function myFunction() {
Browser.msgBox("Hello World!");
}

to this:

function helloWorld() {
Browser.msgBox("Hello World!");
}

Note, it’s convention in Apps Script to use the CamelCase naming convention,
starting with a lowercase letter. Hence, we name our function helloWorld, with a
lowercase h at the start of hello and an uppercase W at the start of World.

Adding a custom menu

In its current form, our program is pretty useless for many reasons, not least be-
cause we can only run it from the script editor window and not from our spread-
sheet. So let’s fix that by adding a custom menu to the menu bar of our
spreadsheet, so that a user can run the script within the spreadsheet without need-
ing to open up the editor window.

This is actually surprisingly easy to do, requiring only a few lines of code. Add the
following 6 lines of code into the editor window, above the helloWorld() function
we created above, as shown here:

function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('My Custom Menu')
.addItem('Say Hello', 'helloWorld')
.addToUi();
}

function helloWorld() {
Browser.msgBox("Hello World!");
}

If you look back at your spreadsheet tab in the browser now, nothing will have
changed. You won’t have the custom menu there yet. We need to re-open our
spreadsheet (refresh it) or run our onOpen() script first, for the menu to show up.

To run onOpen() from the editor window, first select the onOpen function as shown
in this image:

Once you’ve selected the onOpen function, the small triangle button will change
from light gray to black, meaning it can be clicked to run your chosen function:

Now, when you return to your spreadsheet you’ll see a new menu on the right side
of the Help option, called My Custom Menu. Click on it and it’ll open up to show a
choice to run your Hello World program:

My own journey into Apps Script

My friend Julian, from Measure School, interviewed me recently (May 2017) about
my journey into Apps Script and my thoughts on getting started:
How to get started with Google Apps Script (feat. Ben Collins)

Google Sheets script tutorial: more examples

Custom function/maps example

Let’s create a custom function with Apps Script, and also demonstrate the use of
the Maps Service. We’ll be creating a small custom function that calculates the dri-
ving distance between two points, based on Google Maps Service driving
estimates.

The goal is to be able to have two place-names in our spreadsheet, and type the
new function in a new cell to get the distance, as follows:

The solution should be:

Copy the following code into the Apps Script editor window and save. First time,
you’ll need to run the script once from the editor window and click “Allow” to en-
sure the script can interact with your spreadsheet.

function distanceBetweenPoints(start_point, end_point) {


// get the directions
var directions = Maps.newDirectionFinder()
.setOrigin(start_point)
.setDestination(end_point)
.setMode(Maps.DirectionFinder.Mode.DRIVING)
.getDirections();

// get the first route and return the distance


var route = directions.routes[0];
var distance = route.legs[0].distance.text;
return distance;
}

Saving social media data

Let’s take a look at another simple use case for this Google Sheets script tutorial.

Here, I’ve setup an importxml function to extract the number of followers a specif-
ic social media channel has (e.g. in this case a Reddit channel), and I want to save
copy of that number at periodic intervals, like so:

In this script, I’ve created a custom menu (as we did above) to run my main func-
tion. The main function, saveData(), copies the top row of my spreadsheet (the live
data) and pastes it to the next blank line below my current data range as text,
thereby “saving” a snapshot in time.

The code for this example is:

// custom menu function


function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Custom Menu')
.addItem('Save Data','saveData')
.addToUi();
}

// function to save data


function saveData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var url = sheet.getRange('Sheet1!A1').getValue();
var follower_count = sheet.getRange('Sheet1!B1').getValue();
var date = sheet.getRange('Sheet1!C1').getValue();
sheet.appendRow([url,follower_count,date]);
}

See here for a full step-by-step guide to creating and running this script.

Google Apps Script example in Google Docs

GAS is by no means confined to Sheets only, and is equally applicable in the Docs
environment. Here’s a quick example of a script that inserts a specific symbol or
text string into your Doc wherever your cursor is:

We do this using Google App Scripts as follows:

1. Create a new Google Doc


2. Open script editor from the menu: Tools > Script editor...

3. Click on: Create script for > Blank Project

4. In the newly opened Script tab, remove all of the boilerplate code (the
myFunction code block)

5. Copy in the following code:

// code to add the custom menu


function onOpen() {
var ui = DocumentApp.getUi();
ui.createMenu('My Custom Menu')
.addItem('Insert Symbol', 'insertSymbol')
.addToUi();
};

// code to insert the symbol


function insertSymbol() {
// add symbol at the cursor position
var cursor = DocumentApp.getActiveDocument().getCursor();
var element = cursor.insertText('§§');

};

6. You can change the special character in this line

var element = cursor.insertText('§§');

to whatever you want it to be, e.g.

var element = cursor.insertText('( ͡ ° ͜ ʖ ͡ °)');

7. Click Save and give your script project a name (doesn’t affect the running so call
it what you want e.g. Insert Symbol)

8. Run the script for the first time by clicking on the menu: Run > onOpen

9. Google will recognize the script is not yet authorized and ask you if you want to
continue. Click Continue
10. Since this the first run of the script, Google Docs asks you to authorize the
script (I called my script “test” which you can see below):

11. Click Allow

12. Return to your Google Doc now.

13. You’ll have a new menu option, so click on it:


My Custom Menu > Insert Symbol

14. Click on Insert Symbol and you should see the symbol inserted wherever your
cursor is.

Use the Logger class

Use the Logger class to output text messages to the log files, to help debug code.

The log files can be accessed after the program has finished running, by going to
View > Show Logs (or Cmd + Enter, or Ctrl + Enter (on PC)).

The syntax in its most basic form is Logger.log(something in here). This records
the value(s) of variable(s) at different steps of your program.

For example, add this script to a code file your editor window:

function logTimeRightNow() {
var timestamp = new Date
Date();
Logger.log(timestamp);
}

Run the script in the editor window, then View > Show Logs and you should see:

Real world examples from my own work

I’ve only scratched the surface of the outermost epidermis, not even millimeters
deep, of what’s possible using GAS to extend the Google Apps experience.
Here’s a couple of interesting projects I’m working on:

1) A Sheets/web-app consisting of a custom web form that feeds data into a Google
Sheet (including uploading images to Drive and showing thumbnails in the
spreadsheet), then creates a PDF copy of the data in the spreadsheet and automati-
cally emails it to the users. And with all the data in a master Google Sheet, it’s pos-
sible to perform data analysis, build dashboards showing data in real-time and
share/collaborate with other users.

2) A dashboard that connects to a Google Analytics account, pulls in social media


data, checks the website status and emails the user if it goes down, and emails a
summary screenshot as a PDF at the end of each day.

3) A marking template that can send scores/feedback to students with a single click
from within Google Sheets. Check out the how-to post I wrote.

Further Resources

Imagination and patience to learn are the only limits to what you can do and
where you can go with GAS. I hope you feel inspired to try extending your Sheets
and Docs and automate those boring, repetitive tasks!
For further reading, I’ve created this list of resources for information and
inspiration:

Apps Script References

Start writing more advanced scripts with the official Apps Script starter guide – a
more advanced Hello World program!

Official Google Documentation

Google Apps Developer Blog

Google Apps Script for Developers Training Video Course from O’Reilly

Collection of great blog posts relating to GAS

Integrating Google Apps Script with Slack

Using Google Sheets and GAS as a backend database

Alexa rank checker with email notifications in Google sheets

How to Create Custom Functions in Google Sheets

List of some popular Apps Script projects

Communities

Google Docs Help Forum

Google Apps Script G+ community

Desktop Liberation Apps Script community from Bruce Mcpherson

Stack Overflow GAS questions


Google Apps Script Experts

Zig Mandel (GDE)

Bruce Mcpherson (GDE)

Antonio Guzmán Fernández (GDE)

Martin Hawksey (GDE)

Ivan Kutil (GDE)

Romain Vialard (GDE)

James Ferreira (GDE)

Andrew Stillman (GDE)

Andrew Roberts

Amit Agarwal

GDE – Google Developer Experts are experts in their chosen fields (in this case
GAS) and recognized by Google for their outstanding contributions. More info
here.

Books and other miscellaneous tips

Going GAS by Bruce Mcpherson is a newly pub-


lished (i.e. bang up-to-date as of April 2016) book
covering the entire GAS ecosystem, with a specific focus on making the transition
from Office/VBA into Google Apps/GAS. Even if you don’t use Office or VBA much
or at all, it’s still a very useful resource. It’s been a few years since I’ve done any
serious VBA work, but I still found the book very helpful and a great overview of
the GAS environment.

Learning Google Apps Script by Ramalingam Ganap-


athy is another brand new Google Apps Script book,
intended for learning Apps Script. I haven’t used this particular book.

Google Sheets Programming With Google Apps Script by Michael Maguire is an


ebook available through leanpub. I haven’t used this particular book.

I believe other Google Sheets books are older and therefore may advocate depre-
cated code or not follow current best practices. Caveat emptor!

Finally, if you do get into GAS and start writing lots of code, try out this color edi-
tor for your Apps Script window. It’ll change the default white screen to a dark
screen with better highlight and folder options for your projects. This setup is
much more akin to other professional code editors like Sublime Text.

 April 12, 2016  Ben  Spreadsheets  Apps Script, dashboard, Google Sheets

45 thoughts on “Beginner guide to coding with Google Apps


Script”

Jane
June 1, 2016 at 10:32 am

I couldn’t resist commenting. Exceptionally well


written!

Ben 
June 1, 2016 at 3:06 pm

Thank you!

Rishu
March 14, 2018 at 4:53 am

Hey Ben,

I am facing error in code for calculating distance between 2 points


Cannot read property “legs” from undefined. (line 11, file “Code”)
Can you please help

Armando
July 12, 2016 at 7:08 pm

Hi, Im writing some code in google script, but when I open de file, my script
doesn’t work until the first minute i Think, its like there is a delay before the script
really respond to my calls on buttons, do you know why is this happening?

Ben 
July 12, 2016 at 10:16 pm

Hi Armando,

Hmm, there shouldn’t be any substantial delay, certainly not a minute. The script
could be affected by your internet connection speed, but I wouldn’t expect to see
such a big delay, especially if other web services load normally.

Inefficient code, i.e. lots of calls to/from the Google Sheets or other Google ser-
vices, can make a script run slowly, so it’s best practice to minimize the number
of calls required. More reading here at the official Apps Script docs: https://devel-
opers.google.com/apps-script/best_practices

I suggest sharing your question/code on the Apps Script forum here: https://plus.-
google.com/u/0/communities/102471985047225101769 where there’s a communi-
ty of experts who can suggest specific fixes.

Hope that helps.

Ben

vishal
September 28, 2016 at 8:45 am

hi, i want to track a user who copy, cut, or delete the more then 10 cells at once,
please provide me a code or a way how can i do it
Sat
October 26, 2016 at 2:58 am

Hi, Ben,
Thanks for very well written article that even a beginner like myself could under-
stand! What resources/training courses/tutorials on Google App scripts you would
advise to a person that have no previous knowledge of programming.
Thanks,
Sat

Ben 
November 1, 2016 at 5:17 pm

Hi Sat, there’s a list of resources at the end of this post which is where I’d start.
Then try creating your own scripts and googling for answers when things don’t
work. The forums are very helpful at answering specific questions.

Cheers,
Ben

Marwane BERRIS
January 19, 2017 at 2:32 pm

Hi, I’m french, so excuse me for my approximate English …


I’ve tested your “Custom function/maps example” paragraph, but I’ve an error !
When I validate the formula in spreadsheet it says: TypeError: Unable to read the
“legs” property from undefined. (Line 12).

Can you help me ??

Thx

Sebastian Marquez
February 17, 2017 at 4:42 pm

Here’s an answer I found if your still having trouble from http://www.gadget-


sappshacks.com/2014/02/calculating-distance-between-two.html:
———
This happens if the cell being referenced by the function (e.g. cell A8 in the pubic
spreadsheet I provided) is made an invalid location (e.g. “XASD*&^”). So perhaps
one of our locations isn’t something that Google Maps can uniquely identify as a
location. Try cut/pasting it into maps.google.com to see how it responds.
———-

My script was doing the same thing until I opened up Google Maps

Ben 
February 18, 2017 at 6:52 pm

Thanks for sharing your solution Sebastian!

Gary Miller
April 26, 2017 at 5:23 am

I found that if the location is one of several that would be returned from a
Maps search, an error is displayed. No real surprise there. You have to specify
enough detail to make it unique. Here in the UK I was searching for ‘Dover’,
but until I put ‘Dover, Kent’ the distance was not displayed.

Ben 
May 2, 2017 at 10:22 am

Interesting, thanks for sharing Gary. I’ve never taken this function beyond
this very basic example for illustration, but clearly you could improve the er-
ror handling and give this kind of feedback to a user. Cheers!

Stefano
February 15, 2017 at 8:16 am

Hi Ben,

this article is really interesting.

I found the dashboard that connects to a Google Analytics account, pulls in social
media data, checks the website status and emails really amazing and extremely
useful. Do you plan to share it or to make a tutorial on how to built a dashboard
like that?

Thanks,
Stefano

Ben 
February 15, 2017 at 9:22 am

Hey Stefano,

That dashboard is covered in depth in the online dashboard course I’m launch-
ing….next week (20th Feb)! I walk through how to create it step-by-step, includ-
ing the apps scripting.

P.S. There’ll be a special offer for newsletter subscribers next week (sign up form
at the end of this page here).

Cheers,
Ben

Augustiine Agbi
February 27, 2017 at 7:47 am

Very interesting. Am in dire need to learn how to develop a mobile app for e-learn-
ing/assessment. However, I don’t have knowledge of programming. I will appreci-
ate if I can get a step by step guide on programming. Thanks. Augustine

Pingback: What is Google Apps Script ?- Overview

motuandpatlugames.in
March 27, 2017 at 7:11 pm

Very good information. Lucky me I found your blog by accident (stumbleupon).


I have saved it for later!
Gary Miller
March 30, 2017 at 9:19 am

I get an error: Cannot call Browser.msgBox() from this context; have you tried Log-
ger.log() instead? (line 2, file “Code”) when I try to run the Hello World script. Fail-
ing at the first attempt does not feel good. Do you know what the problem is?

Ben 
March 30, 2017 at 4:00 pm

Hmm, not sure. Did you get the Authorization Required popup? What’s the exact
error message you’re getting? The popup will show up in your Sheet browser
tab, not the code editor tab, so you need to return to that one to the Hello World
message.

Gary Miller
March 31, 2017 at 5:30 am

I did not get the authorisation pop up when I ran the script. However, i have
tried it today and hit the debug icon, instead of run. This DID produce the au-
thorisation pop up, and the function has run fine. Curious behaviour!

Ben 
March 31, 2017 at 10:50 am

Yes, that is strange! Great it’s working for you now

Pingback: Beginner Guide to APIs with Google Sheets and Google Apps Script

Pingback: Google Sheets and Mailchimp integration using Apps Script and the
Mailchimp API

Pingback: How to build a real-time sales dashboard for E-junkie with Google
Sheets and Apps Script
Pingback: Google Sheets, Apps Script and Data Studio Resources: The Ultimate List
for 2017 - Ben Collins

Pingback: Reply to Google Forms survey respondents direct from Google Sheets

Pingback: How to create a waterfall chart in Google Sheets - Ben Collins

Pingback: How to load Facebook post data into Google BigQuery - Need a
dashboard with Google Data Studio ?

Robert L. Crocker
June 26, 2017 at 2:19 pm

Very useful info..

Had one weird problem when I tried the first UI example..

When I created the menu as you did

e.g.

var ui = SpreadsheetApp.getUi();
ui.createMenu(‘My Custom Menu’)
.addItem(‘Say Hello’, ‘helloWorld’)
.addToUi();

I got a “.createMenu undefined” error…

didn’t shake the error message until I rewrote to

var ui = SpreadsheetApp.getUi().createMenu(‘MyMenu’)
.addItem(‘Hello There’, ‘helloWorld’)
.addToUi();
and it all worked fine.
Have no idea what the difference is.
I’ve had this kind of thing happen before in app script though…
in particular when I was testing for results less than a particular variable using
var1 0 and everything worked OK.

so it’s good to teach multiple ways of doing the same thing.

Nihar
June 29, 2017 at 1:42 am

Great Post
Thanks a lot it helped me a lot
I am also going to share it to my friends and over my social media.
Also,
Hackr.io is a great platform to find and share the best tutorials and they have a
specific page for Google apps script

This might be useful to your readers: https://hackr.io/tutorials/learn-google-apps-


scripts

Shilpa
July 5, 2017 at 1:12 am

Hi,
We have a container bound script and would like to password protect the Script
Editor.Is there any way to do this or a workaround available to ensure that only
the developer can access the Script Editor?

Mike T
August 23, 2017 at 2:34 pm

This is awesome – Thanks!

I’m running in to an error with the Map distance problem.


It initially worked, and then when I tried it again with new values, it stated:
“TypeError: Cannot read property “legs” from undefined.”

Even when I put the old values back in, it would no longer work.
Any suggestions?

Ben 
August 28, 2017 at 11:31 am

Hey Mike,

Have a look at this comment thread further up the post: https://www.benl-


collins.com/spreadsheets/starting-gas/#comment-17176

It’s most likely caused by ambiguity in the leg, which this basic function isn’t able
to deal with.

Cheers,
Ben

Mike T
August 28, 2017 at 1:24 pm

Thanks for the quick reply!

The strange thing is that even the two points that initially worked and returned
the distance, also stopped working after I tried other destinations. It only
worked the first time and then everything seemed to break.

Steven De Roover
September 4, 2017 at 6:30 am

What a lovely article. I’m just starting to explore all the possibilities of Google App
Scripting. I don’t have any main goal yet, so I’m just fiddling around a bit.

For starters I’d like to know whatever is possible with an app inside a google site,
and I didn’t find any documentation on how to implement custom UI controls on
the properties on the embedded app.
To clarify: I add a script in my google site, then on a page I add a “Google Script
App”, and add that script I just made. Then for that added ‘widget’, you can click
on the edit button. I’d like to know how to add my custom settings on that page.
I know it’s possible, as other existing widgets can do this too.

Any help on this one?

Ben 
September 5, 2017 at 4:38 pm

Hey Steven,

I’ve never used Google Sites, so I’m not sure the answer to your question. I’d sug-
gest posting your question to the Google Apps Script forum where I’m sure some-
one will have some input:
https://plus.google.com/u/0/communities/102471985047225101769

Cheers,
Ben

Pingback: Community Connectors: Native data connectors for Google Data Studio

Pingback: How to add a hyperlinked index sheet to your large Google Sheet
workbooks - Ben Collins

Brian Pugh
November 21, 2017 at 12:53 pm

I am new to scripting. I have 12 functions in a single script. I cannot find a suitable


answer to this question:

How can I link my scripts so that all 12 run sequentially?

Thank you very much!

Ben 
November 28, 2017 at 12:52 pm

Hey Brian,
I can understand your frustration, I was there once too

You can call your 12 functions inside another, sort of master execution function,
if you will, like this:

function runFuncs() {
// put your 12 functions in here...
func1();
func2();
// etc...
}

function func1() {
Logger.log("Hello!")
}

function func2() {
Logger.log("Goodbye!");
}

where func1 and func2 would be the first two of your 12 functions. When you
run runFuncs(), it will execute those functions inside of it, func1 and func2 in
this case, but could be all your 12.

Hope that helps!

Ben

Abdul Sami
December 7, 2017 at 6:12 am

I am a new user to google sheets and I love working with excel automation and ad-
vance excel. I searched about google sheet programming, and your this article be-
come very beneficial to me.

Great work!

Ben 
March 14, 2018 at 12:05 pm

Thanks Abdul!

Pingback: Slow Google Sheets? Here are 27 techniques you can try right now

Pingback: Automatically issue Teachable course certificates with Apps Script

Privacy Policy / Proudly powered by WordPress

More than one instance of Sumo is attempting to start on this page. Please check that you are only
loading Sumo once per page.