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
$43.99
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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Black & white paperback book shipped to your address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Black & white paperback book shipped to your address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

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 the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela