Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Learning Google Apps Script
Learning Google Apps Script

Learning Google Apps Script: Customize and automate Google Applications using Apps Script

By Ramalingam Ganapathy
$15.99 per month
Book Mar 2016 232 pages 1st Edition
eBook
$35.99 $24.99
Print
$43.99
Subscription
$15.99 Monthly
eBook
$35.99 $24.99
Print
$43.99
Subscription
$15.99 Monthly

What do you get with a Packt Subscription?

Free for first 7 days. $15.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details


Publication date : Mar 18, 2016
Length 232 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781785882517
Category :
Table of content icon View table of contents Preview book icon Preview Book

Learning Google Apps Script

Chapter 1. Introducing Google Apps Scripts

I know there may not be a single person in the world who has access to the Internet who has not used at least one of Google's products or services in their lifetime.

Google is known for its famous search engine, the video serving portal YouTube, and now by its numerous web applications, namely Gmail, Calendar, Drive, Docs, Sheets, and Forms. It also provides cloud computing and other software services.

The word "Google" has even become a verb, referring to conducting a web search. Nowadays, you hear people saying "I Googled something" rather than "I searched the web for something". In this chapter, you will learn about Google Applications, Application Scripts, and how to create a custom formula/function.

Google Applications


Google Applications are a collection of applications, namely Gmail, Calendar, Drive, Docs, Sheets, and Forms. From now on, we will use the term "Google Apps" or just "Apps".

Before we start, I'll quickly answer a few questions you may have:

  • Where do all these Apps run? On your computer?

    No, all these Apps run on Google's Cloud-based servers.

  • How can you get access to these applications?

    You can interact with these Apps through web browsers. No special hardware or software installations are required except for a modern web browser installed on your desktop, laptop, tablet, or smartphone.

Google Apps Script


You can customize or automate Google Apps using the JavaScript scripting language with Google-defined classes, known as Google Apps Script (GAS). Google implements GAS based on JavaScript 1.6 with some portions of 1.7 and 1.8. The GAS services and APIs provide easy access so users can automate tasks across Google products and third-party services.

You can write code in Google Docs, Sheets, and Forms using GAS and can automate tasks similar to what Visual Basic for Applications does in Microsoft Office. However, GAS runs on Google's server and the results are rendered in your browser. The integrated script editor allows you to edit and debug your scripts within your browser, and you do need not install anything. You can activate your debugged and tested script functions to run either based on your interactions or based on a trigger in response to an event or timed intervals (in minutes, hours, days, weeks, future dates, and so on). These events include onOpen, onEdit, onInstall, and many more. GAS is also used to create add-ons for Docs, Sheets, and Forms.

GAS can help you with every aspect of automating a task—you can even use it to order a pizza at predetermined date/time!

Visual Basic for Applications

Microsoft implements Visual Basic for Applications (VBA) to help automate Office applications such as Excel and Word. For each respective application, VBA is known as Excel VBA or Word VBA and so on. Using Excel VBA, you can create macros for Excel known as "Excel macros". GAS is for Google Applications, and operates in the same way as VBA does for Microsoft Office applications. Although both VBA and GAS do not require a separate compilation process, they are very different scripting languages and use different programming APIs, methods, and properties.

I hope many of you are familiar with using VBA for Office applications; if not, then never mind—that's not an obstacle to learning GAS.

The advantages of GAS over VBA

  • Version-independence: Sheets/Docs along with scripts are automatically saved in the cloud, attached to your Google account, and accessible from any computer with a browser. There is no need to worry whether the other computer has the same version of Sheets/Docs installed or not, whereas we can never be sure that one version of the Excel/Word macros will work on another version.

  • Platform-independence: When you create VBA macros in Excel/Word on the Windows platform, they may not work on the Mac platform and vice versa. With Google Sheets/Docs, it doesn't matter what platform you're working on—it'll work.

The limitations of GAS

GAS runs on Google's server, so it cannot run continuously for more than six minutes (this may vary in the future). All of your functions should finish running and should return results within this time limit. Don't panic, as you'll learn how to use triggers effectively to overcome these limitations later.

In the following sections, we will take a look at the most popular Google Apps and how we can use GAS to customize and/or automate tasks.

Google Drive


Google Drive is a file storage application, which from now on we will just refer to as "Drive", where you can store and synchronize your files on Google's server. Let's look at some of the advantages of using Drive:

  • You can edit and share Google Docs, Sheets, and Forms with your friends or collaborators in real time.

  • You can even stop editing a document on one of your desktops and continue with your smartphone or tablet, and vice versa, no matter where you are and what device you are using. This is possible because your files are stored on Google's Cloud server.

  • Files created with Google Apps are stored in Drive with Google's native formats and extensions. For example, Google Docs (documents) files are .gdoc, Google Sheets (spreadsheets) are .gsheet, and so on.

  • In addition to Google's native files, you can also store or upload any other type of file from your desktop to Google Drive.

    Note

    If you would like to synchronize files on your computer or devices with Drive, then you can install special software called Google Drive Client Application. While this application is running on your computer or device, it synchronizes files stored locally with the same files in Drive.

You may be wondering, what is the purpose of synchronizing files? Sometimes you may need to, or someone may ask you to, parse a CSV file stored on a desktop using GAS to process the data and organize it into a Sheet. In this case, GAS won't execute on the desktop, but it can on the Google server. This way you can access your Drive files and parse data within your synchronized CSV file. You don't have to upload the CSV file manually every time to Drive.

The following screenshot shows the Drive folder view:

Gmail


Gmail is the most popular web-based e-mail service and is provided by Google. With it, occasionally composing and sending e-mail messages manually to one or a few people is not a problem. But what if you want to send an e-mail at a predefined time when you are not awake or to multiple recipients? Consider the following scenarios:

  • You want to send a surprise birthday greeting to your friend at a fixed time; neither earlier nor later

  • You need to send customized e-mails to hundreds of people at a time

  • You need to send e-mails periodically

For all these scenarios, GAS has the answers:

  • Using GAS, you can build a mail merger application to send e-mails with customized greetings or messages to n number of people.

  • You can extract information buried in e-mails from your inbox and store and organize them in Google Sheets or Docs.

  • You can even convert the data or contents of a Google Sheet or Docs to a PDF or any other file format and send it as an e-mail attachment, or just save the created file in Drive and include only the file's URL as a hyperlink in e-mail messages.

  • In addition, GAS also allows you to mark selected messages as important, or starred. You can also add, delete, and update your Gmail Contacts using the Contacts service.

The following screenshot shows how Gmail classifies or groups messages with labels:

Google Calendar


Google's online Calendar service is integrated with Gmail. GAS provides access to Calendar service by using the CalendarApp class. Using GAS code, you can access and modify your Calendar and those you have subscribed to. Using GAS, you can create Calendar events and invite your friends programmatically. Alternatively, you can grab event details and populate them in Sheets.

Google Docs


Google Docs is a word processing program, and runs on web-based software within the Google Drive service. Docs allows you to create and edit documents online while collaborating with other users in real time. Using GAS, you can create documents, format the contents, translate them to other language, save them in Drive, or e-mail them to your friends.

Google Sheets


Google Sheets is a spreadsheet program much like Microsoft Excel. You can create Sheets, share them with others, and edit them in real time. Google provides built-in formulae/functions in Sheets. You can also create your own simple to complex formulae. In other words, you can create custom formulae. Using the SpreadsheetApp class in your GAS code, you can interact with other applications.

Google Apps services


Google provides Apps services to enable GAS to interact with the Apps. Almost all of the Apps provide one or more services. You can use these service classes in your GAS code to customize or automate Apps. Services are grouped as basic and advanced. You can use basic services directly, but for advanced services you need to enable them before using them. You will see how to enable them later on.

Creating Google Sheets in Drive and sharing them with your friends and the public

Here are the steps to create a Google Sheet:

  1. Run your favorite browser and type https://drive.google.com/ in the address bar.

    Tip

    In order to use Google Drive, you should have a Google account. If you don't have an account, then create one.

  2. Now the Google Drive page will open. In the left pane, click on the NEW button and on Google Sheets:

  3. After creating a new Sheet, right-click on it (Windows) or context click (Mac) and select the Share... option:

  4. A new pop-up window will open as shown in the following screenshot. After that, enter the e-mail address, or addresses, with which you would like to share the document. Finally, click on the Done button:

    Google will send a share notification to your friend(s). When your friend(s) click on the access link provided, they will get access to your document.

Congratulations! You have created a new Sheet and successfully shared it with your friend(s).

Script projects


Scripts are organized as projects. Projects can be of two types, standalone and bounded to a gtype (Google Drive native file type, such as Sheets, Docs, and Forms) file. Standalone scripts are created in a separate script file, you can see these files listed among other files in Drive. Bounded scripts are embedded within individual gtype files and created using the respective applications. As you can see, the standalone script files, among other files in Drive, you can open directly from Drive, but bounded script can be opened within respective applications only. However, bounded script will have more privileges over parent file than standalone scripts. For example, you can get access to the active document within bounded scripts, but not within standalone scripts.

Creating standalone script projects

To create a standalone script file follow these steps:

  1. Follow the steps as described in the Creating Google Sheets in Drive and sharing them with your friends and the public section.

  2. Navigate to NEW | More | Google Apps Script rather than the spreadsheet, as shown in the following screenshot:

  3. A new untitled project will open in a new browser tab or window. The new project includes one code file, Code.gs, with a blank function, myFunction, as shown in the following screenshot:

  4. To save or rename the new project, press Ctrl + S on your keyboard or click on the Save icon (floppy disk) in the editor. If you are saving the project for the first time then a prompt will appear to enter a new project name. Enter the project name (whatever you like) and click on the OK button. The new script file will be saved in the current folder:

Creating new projects in Sheets

Create a new Sheet or open the existing one. You will see a number of menu items at the top of the window. Now, follow these steps:

  1. Click on Tools and select Script editor..., as shown in the following screenshot:

  2. A new browser tab or window with a new project selection dialog will appear, as shown in the following screenshot:

  3. Click on Blank Project or close the dialog (you do not need to always select Blank Project, just this time). A new untitled project will open in a new browser tab/window.

  4. Save the project as described in the preceding section.

    Tip

    Although you can create as many bounded projects as you like, one project per file is enough. Creating just one project per file may help you to avoid problems with duplicate function and variable names.

Congratulations! You have created a new script project. By following the preceding steps you can create script projects in Docs and Forms too.

Creating a custom formula in Sheets

Open the spreadsheet you created earlier and make the following changes:

  1. In columns A and B, type a few first and last names.

  2. In cell C2, type (including the equals sign) =CONCATENATE(A2," ", B2).

Now you can see the first name and last name in cells A2 and B2 respectively, concatenated with a space in between.

CONCATENATE is Google Sheet's built-in formula. You can also create your own, called custom formula:

  1. Open the script editor and copy-paste this code:

    function myFunction(s1,s2) {
      return s1 + " " + s2;
    }

    Here is the screenshot for the same:

  2. Press Ctrl + S on your keyboard or click on the Save icon in the editor to save the script.

  3. Now return to the spreadsheet, and in cell C2, type =myFunction(A2,B2).

    This works in exactly the same way as the built-in formula. You can extend your formula to other cells below C2. This is a simple formula, but you can create complex formulae as per your requirements.

  4. Your custom formula should return a single value or a two-dimensional array. The following screenshot shows how a custom function will work:

Congratulations! You have created a custom formula.

Note

To add code completion and/or tooltips for your custom function, add the following comments at the preceding lines of code in the function:

/**
 * Concatenates two strings
 *
 * @customfunction
 */
function myFunction(s1,s2){
      …

Google Forms


Google Forms is a Google App that you can use to collect information from your users. User responses or answers are collected and stored as responses in the Form itself and then can be populated in the connected Sheet. You can also change the response's target Sheet when required. You can create Google Forms dynamically using GAS.

Creating Forms within Google Sheet

In the spreadsheet you created earlier, click on the Tools menu and select the Create a form option. A new Form will be created and is bound to a new Sheet automatically. The new Sheet's name will be similar to Form Responses 1. In the new Form, create form fields with headings exactly same as in the Sheet's column headers:

On completion, try submitting the data using a live Form.

Some research

If you are given a document's ID or key, something like 11CEeHWygGKqxGS7jmQzLpeO7Fs3cjetT4HTrWXHTDSU, can you open the document, provided it has been shared with the public?

Tip

Every Google Doc, Sheet, folder, and project has an ID or key, which you can get from the corresponding item's URL.

Summary


In this chapter, you learned about Google Apps and got an introduction to GAS, as well as how to create a project and custom formulas. There are many more Google Apps available but we just covered the most popular ones. It will not be hard to adopt the same scripting concepts and principles for other Apps. In the next chapter, you will learn to create basic elements such as custom menus, dialogs, and sidebars.

Left arrow icon Right arrow icon

Key benefits

  • Gain insight into customizing and automating Google applications with JavaScript
  • Create add-ons for Google Sheets, Docs, or Forms; automate your workflow; integrate with external APIs; and more.
  • A step-by-step guide to building real-world solutions

Description

Google Apps Script is a cloud-based scripting language based on JavaScript to customize and automate Google applications. Apps Script makes it easy to create and publish add-ons in an online store for Google Sheets, Docs, and Forms. It serves as one single platform to build, code, and ultimately share your App on the Web store. This book begins by covering the basics of the Google application platform and goes on to empower you to automate most of the Google applications. You will learn the concepts of creating a menu, sending mails, building interactive web pages, and implementing all these techniques to develop an interactive Web page as a form to submit sheets You will be guided through all these tasks with plenty of screenshots and code snippets that will ensure your success in customizing and automating various Google applications This guide is an invaluable tutorial for beginners who intend to develop the skills to automate and customize Google applications

What you will learn

[*] Learn about the Google Apps script platform and work with scripts to develop Google apps [*] Create custom menus and dialogs [*] Parse and send emails [*] Generate Google calendar events [*] Build Translator and RSS reader applications [*] Develop interactive web pages [*] Design interactive web-forms [*] Form a workflow application

What do you get with a Packt Subscription?

Free for first 7 days. $15.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details


Publication date : Mar 18, 2016
Length 232 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781785882517
Category :

Table of Contents

16 Chapters
Learning Google Apps Script Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
About the Reviewer Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
Introducing Google Apps Scripts Chevron down icon Chevron up icon
Creating Basic Elements Chevron down icon Chevron up icon
Parsing and Sending E-mails Chevron down icon Chevron up icon
Creating Interactive Forms Chevron down icon Chevron up icon
Creating Google Calendar and Drive Applications Chevron down icon Chevron up icon
Creating Feed Reader and Translator Applications Chevron down icon Chevron up icon
Creating Interactive Webpages Chevron down icon Chevron up icon
Building a Workflow Application Chevron down icon Chevron up icon
More Tips and Tricks and Creating an Add-on Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.