SlideShare a Scribd company logo
Google Apps Scripts
Power up your Google Suite Course Guide
https://www.udemy.com/learn-google-apps-script
INSTRUCTOR:
LAURENCE SVEKIS
Course instructor : Laurence Svekis
- Over 300 courses in technology and
web applications.
- 20 years of JavaScript web
programming experience
- 500,000+ students across multiple
platforms
- Digital instructor since 2002
READY TO HELP YOU LEARN and
ANSWER ANY questions you may
have.
Google Apps Scripts Course Guide
This guide is designed to supplement the
Google Apps Script
It includes source code that follows the lessons of the course. One of the best ways to learn is to try the code out
for yourself. Thanks for taking the course, if you have any questions or need clarification on the content please
let me know in the Q&A section.
Happy Coding …..
Introduction to Google Apps Script
https://developers.google.com/apps-script/
Increase the power of your favorite Google apps —
like Calendar, Docs, Drive, Gmail, Sheets, and
Slides.
Apps Script is based on JavaScript 1.6, (1.7 and
1.8). Many basic JavaScript features in addition to
the built-in and advanced Google services. Apps
Script code runs on Google's servers (not client-
side, except for HTML-service pages), browser-
based features like DOM manipulation or the
Window API are not available.
Create a Script - Google Sheets
To begin you must have a Google Account.
1. Log into your Google Account, create a new
spreadsheet.
https://docs.google.com/spreadsheets/u/0/
2. Open blank sheet and give it a name
3. Add some random data with headings in
first row.
Create a Script - Marco
1. In the tools bar select marco.
2. Bold some of the cells in your sheet.
3. Change color of items in cells.
4. Record marco and give it a name
5. Select Edit Script at the bottom
Edit a Script - Marco
You can also access the script now under the
tools tab and hit script editor. You will see the
Marco you created in the Marcos menu.
If you run the marco it will ask you for
permissions.
Edit a Script - Apps Script Editor - Try IT
In the menu under tools click script editor
Open the editor and you will open it in the online
Apps Script IDE. Welcome to Google Apps Script.
You will see code with a function named the same
as the Marco. Inside is Google Apps Script. Make
some changes SAVE and go back to the
spreadsheet. Run the Marco, see what happens.
function changetext() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('A4:D6').activate();
spreadsheet.getActiveRangeList().setFontWeight('bold')
.setFontColor('#0000ff');
};
CHANGED TO
spreadsheet.getRange('A1:D6').activate();
spreadsheet.getActiveRangeList().setFontStyle('italic')
.setFontColor('red');
One More Marco….
Take two columns with numbers, record a macro
adding the numbers and returning a sum in a new
column. Open the script editor and update the +
to *. Run the marco again.
function adder() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('G2').activate();
spreadsheet.getCurrentCell().setFormula('=SUM(E2+F2)');
spreadsheet.getActiveRange().autoFill(spreadsheet.getRange('G2:G7'),
SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
spreadsheet.getRange('H7').activate();
};
CHANGE TO
spreadsheet.getCurrentCell().setFormula('=SUM(E2*F2)');
Run the App Script in the Editor
Update the adder function adding at the end the
code from the other marco, changing font color
and style. Click Save and in the drop down select
the adder function. Press the play/run button.
function adder() {
var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('G2').activate();
spreadsheet.getCurrentCell().setFormula('=SUM(E2*F2)');
spreadsheet.getActiveRange().autoFill(spreadsheet.getRange('G2:G7'),
SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
spreadsheet.getActiveRangeList().setFontStyle('italic')
.setFontColor('blue');
};
Apps Script
Apps Script can -
● Write custom functions and macros for
Google Sheets.
● Add custom menus, dialogs, and sidebars to
Google Docs, Sheets, and Forms.
● Publish web apps — either standalone or
embedded in Google Sites.
● Interact with other Google services,
including AdSense, Analytics, Calendar,
Drive, Gmail, and Maps.
● Build add-ons to extend Google Docs,
Sheets, Slides, and Forms
Two types of scripts Bound script and Standalone
script.
Currently we have created a bound script…. Let’s
create a standalone script.
Go to URL https://script.google.com/home
Select New Script button
Create Standalone Script Custom Functions
Open online IDE editor. This is where you write
scripts.
1. Add a name for your script.
2. Update the Code.gs myFunction with code.
3. Press the run button.
4. Accept permissions check your email!
function myFunction() {
var doc = DocumentApp.create('First Document');
doc.getBody().appendParagraph('Hello World');
var url = doc.getUrl();
var email = Session.getActiveUser().getEmail();
var subject = doc.getName();
var body = 'The document you just created : ' + url;
GmailApp.sendEmail(email, subject, body);
}
Document ID
https://developers.google.com/apps-
script/reference/document/
Every Google document has a unique ID. Easiest
way to get it is open the document and get it from
the URL.
Use getBody() method and appendParagraph()
Try with JavaScript Method for Date().
function updater(){
var doc =
DocumentApp.openById('15gBfW32K8wZleJC5DtYWeEGBm3CUbSQl7jBlh0ffZfM'
);
doc.getBody().appendParagraph('Another Paragraph Just added');
var now = new Date();
doc.getBody().appendParagraph('Another Paragraph Just added at '+ now);
}
Document Service
https://developers.google.com/apps-
script/reference/document/
This service allows scripts to create, access, and
modify Google Docs files. Each services has
classes and methods in addition to allowable
attributes.
Use Logger.log to debug and get data in the log.
Use Logger.log
function docIDer() {
var doc =
DocumentApp.openById('15gBfW32K8wZleJC5DtYWeEGBm3CUbSQl7jBlh0ffZfM');
var id = doc.getId()
Logger.log(id);
}
JavaScript in Google Apps Script.
Google Apps Script is based on JavaScript, next
few lessons will review core JavaScript
fundamentals and how it relates to Apps Script.
Apps Script is based on JavaScript 1.6, (1.7 and
1.8). Many basic JavaScript features in addition to
the built-in and advanced Google services. Apps
Script code runs on Google's servers (not client-
side, except for HTML-service pages), browser-
based features like DOM manipulation or the
Window API are not available.
JavaScript - Variables/Data Types
The var statement declares a variable, optionally
initializing it to a value.
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Statements/
var
Variables are one of the most fundamental
notions. Stores the value in memory and can be
accessed later in the code using the variable.
● JavaScript is Case Sensitive
● camelCase when writing JavaScript variables
● Can’t use reserved words
● No Spaces in variable name
● Can’t start with digit only letter, $, or _
Use Logger.log
function jsVar(){
var myString = "Hello World";
var myNumber = 10;
var myBoolean = true;
Logger.log(myNumber + myNumber);
Logger.log(myString + ' ' + myNumber);
Logger.log(typeof myBoolean);
}
JavaScript - Arrays
Arrays and objects allow us to hold multiple values
in the same variable. Can be used to make more
complex data structures, all data types allowed
within.
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Global_Objec
ts/Array
Arrays have built in methods that allow you to do
manipulate the array and more.
function jsMulti(){
var fruits = ['Apple', 'Banana','Orange','Pear'];
Logger.log(fruits.length);
fruits.forEach(function(item, index, array) {
Logger.log(item, index);
});
var addLast = fruits.push('Grape');
var removelast = fruits.pop();
var removeFirst = fruits.shift();
var addFirst = fruits.unshift('Peach');
var pos = fruits.indexOf('Banana');
Logger.log(pos);
Logger.log(fruits);
}
JavaScript - Objects
An object is a collection of related data and/or
functionality (which usually consists of several
variables and functions — which are called
properties and methods when they are inside
objects.
https://developer.mozilla.org/en-
US/docs/Learn/JavaScript/Objects/Basics
function jsObject() {
var car = {
make: 'ford'
, model: 'mustang'
, year: 2000
, price: 50000
, color: 'red'
, tires: true
, drive: function () {
Logger.log('its driving');
}
, instructions: ['turn key', 'put in gear', 'press gas pedal', 'turn wheel as needed']
};
Logger.log(car);
car.drive();
}
JavaScript - Functions
Functions are one of the fundamental building
blocks in JavaScript. A function is a JavaScript
procedure—a set of statements that performs a
task or calculates a value.
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Guide/Functions
We’ve been using functions throughout the
lessons. Run a block of code. Function
declarations load before any code is executed
while Function expressions load only when the
interpreter reaches that line of code.
You can pass in values as arguments and have
return within the function.
function myFunction() {
const message1 = function (mes) {
Logger.log(mes);
}
message1('hello');
message1('welcome');
message1('bye bye');
function message2(mes) {
Logger.log(mes);
}
message2('hello');
message2('welcome');
message2('bye bye');
function message3(mes) {
return 'Great job on the ' + mes;
}
Logger.log(message3('code'));
}
JavaScript - Conditions
The conditional (ternary) operator is the only
JavaScript operator that takes three operands.
This operator is frequently used as a shortcut for
the if statement.
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Operators/C
onditional_Operator
The if statement executes a statement if a
specified condition is truthy. If the condition is
falsy, another statement can be executed.
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Reference/Statements/i
f...else
function myCondition() {
var age = 26;
var beverage = (age >= 21) ? "Beer" : "Juice";
Logger.log(beverage);
function testNum(a) {
if (a > 0) {
return "positive";
}
else {
return "NOT positive";
}
}
Logger.log(testNum(5));
Logger.log(testNum(-5));
}
JavaScript - Loops and iteration
Loops offer a quick and easy way to do something
repeatedly.
https://developer.mozilla.org/en-
US/docs/Web/JavaScript/Guide/Loops_and_iterat
ion
function myLoops() {
for (var step = 0; step < 5; step++) {
Logger.log('Step #' + step);
}
var i = 0;
do {
i++;
Logger.log('Counter ' + i);
} while (i < 5);
}
IDE Online Editor File Tab
Cloud based debugger for debugging App Scripts
in the web browser.
Same for both Bound scripts and Standalone
scripts.
● Create a script file
● Create an HTML file call it index
● Open index and write some HTML code
Under File tab you will find main project settings
and able to create new files.
IDE Online Editor Edit Tab
● Press Content assist you will see the content
popup window.
● In your gs file create a function that outputs
the current date in the Logger.
● Click Current Projects Triggers. In the new
window press + Add Trigger - bottom right
side
● Add trigger to project select function with
time, Time-Driven, Minutes timer, Every
minute and press save.
Under Edit tab edit options like find and replace
and content assist. Triggers.
function whatisthetime() {
var now = new Date();
Logger.log(now);
}
IDE Online Editor View Tab
You can adjust your environment as well as see
logs here.
Under View tab Logs and control options.
IDE Online Editor Run Tab
● Click on your code where the line numbers
are, add the red dot.
● Select run and then the function
● Select debug and then the function. Notice
the popup window at the bottom for
debugger. Stops on red indicator allows you
to debug your code.
● Press continue on the menu will run to next
breakpoint if there is or complete.
Under Run tab allows you to execute functions.
function whatisthetime() {
var now = new Date();
Logger.log(now);
Logger.log(now);
}
IDE Online Editor Publish Tab
Deploy your Google Web app, several options for
deployment.
● Add code doGet() function
● Click Deploy as web app
● Click latest code - developer version
● Copy web app URL in your browser.
● Serve Page content from index file.
https://developers.google.com/apps-script/guides/html/
Under Publish tab allows you to create web apps
to publish.
function doGet(){
var textOutput = ContentService.createTextOutput("Hello World!")
return textOutput
}
function doGet() {
return HtmlService.createHtmlOutputFromFile('index');
}
Web App Dynamic Code
Update your HTML index file code with <?= ?>
This allows you to run Google Script directly in
your client side.
Update doGet() to include evaluate() method to
run the code.
Update who has access to the app, to allow others
to see the app at the URL
Use the same developer URL or publish a new
version to your web app. Same URL with new
version code.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Hello World</h1>
<p>Just some HTML nothing to see here</p>
<div>Current Date <?= new Date() ?>.</div>
</body>
</html>
function doGet() {
return HtmlService
.createTemplateFromFile('index')
.evaluate();
}
IDE Online Editor Resources and Help
Resources allows you to select existing libraries
and bring in using Advanced Google Services.
More advanced concepts than we are covering in
this course.
Shortcuts menu bar does all the common main
menu stuff with the icons.
Help Tab provides more info on Google Apps
Script.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Hello World</h1>
<p>Just some HTML nothing to see here</p>
<div>Current Date <?= new Date() ?>.</div>
</body>
</html>
Document Service
https://developers.google.com/apps-
script/reference/document/
This service allows scripts to create, access, and
modify Google Docs files. Each services has
classes and methods in addition to allowable
attributes.
getParagraphs()
https://developers.google.com/apps-
script/reference/document/body#getParagraphs(
)
Retrieves all the Paragraphs contained in the
section (including ListItems).
Use Logger.log
getText()
getParagraphs()
function paraUpdater() {
var doc = DocumentApp.openById('[DOCID]');
var bodyElement = doc.getBody();
var allParagraphs = bodyElement.getParagraphs();
Logger.log(allParagraphs);
for (var i = 0; i < allParagraphs.length; i++) {
Logger.log(allParagraphs[i].getText());
}
}
Dialogs and custom UI buttons
Create a new document, under tools tab select
script editor.
onOpen() runs by default when the doc opens.
https://developers.google.com/apps-script/guides/menus
Add menu item and create a simple function to
ask a UI question. You need to refresh your
document to see the new ui or run the onOpen()
Code will send an email to you if you say yes.
function onOpen() {
DocumentApp.getUi().createMenu('Advanced').addItem('Create', 'myFun').addToUi();
}
function myFun() {
var ui = DocumentApp.getUi();
var result = ui.alert('Are you having fun?', 'Is the Course everything you expected',
ui.ButtonSet.YES_NO);
var result = ui.alert('Would you like an email sent to you', ui.ButtonSet.YES_NO);
if (result == ui.Button.YES) {
var recipient = Session.getActiveUser().getEmail();
GmailApp.sendEmail(recipient, 'You got this', 'Great job it worked from the Google
Doc.');
ui.alert('Email sent to .' + recipient);
}
else {
ui.alert('No email sent.');
}
}
Document as PDF
The following code will create your document as a
PDF on your drive and allow you to send to your
email.
Create the UI button and show the popup alert.
Get users email
Create file on gDrive
Send the file in an email.
Try the code below to see how you can convert
your doc into a PDF store to your drive and send it
in an email.
function myFun() {
var doc = DocumentApp.getActiveDocument();
var ui = DocumentApp.getUi();
var result = ui.alert('Would you like to save (Name:' + doc.getName() + '.pdf) as
PDF?', ui.ButtonSet.YES_NO);
if (result == ui.Button.YES) {
var docblob = DocumentApp.getActiveDocument().getAs('application/pdf');
docblob.setName(doc.getName() + ".pdf");
var file = DriveApp.createFile(docblob);
ui.alert('Your PDF file is available at ' + file.getUrl());
var recipient = Session.getActiveUser().getEmail();
var message = "Your new document is attached";
MailApp.sendEmail(recipient, 'PDF Doc', message, {
name: 'New ' + doc.getName() + '.pdf created'
, attachments: [file]
});
}
else {
ui.alert('No PDF you cancelled.');
}
}
Spreadsheet Service
https://developers.google.com/apps-
script/reference/spreadsheet/
This service allows scripts to create, access, and
modify Google Sheets files.
Create a new spreadsheet, add a function that
gets the sheet name.
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
Logger.log(ss.getName());
var sheet = ss.getActiveSheet();
Logger.log(sheet.getName());
}
Spreadsheet Data
Add some content to your sheet. Lets get it in
code. Get all the content and then get selected
content from the active range.
Notice the array format [] and then each row []
[[2.0, Joe, Smith, example2@exampleEmail.com, 2.0], [3.0, Jane, Doe,
example3@exampleEmail.com, 3.0], [4.0, John, Doe,
example4@exampleEmail.com, 5.0]]
function getContent(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var data1 = sheet.getDataRange().getValues();
Logger.log(data1);
var data2 = sheet.getActiveRange().getValues();
Logger.log(data2);
}
Spreadsheet Add UI
Create a new sheet dynamically.
Add the menu UI option and invoke the function to
ask for a new sheet by name.
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('Adv')
.addItem('Update', 'myFun')
.addToUi();
}
function myFun() {
var ui = SpreadsheetApp.getUi();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var response = ui.prompt('Name of Sheet', 'Create name of sheet?',
ui.ButtonSet.YES_NO);
if (response.getSelectedButton() == ui.Button.YES) {
var newNamer = response.getResponseText();
Logger.log('The new sheet name is %s.', newNamer);
var yourNewSheet = ss.getSheetByName(newNamer);
if (yourNewSheet != null) {
ss.deleteSheet(yourNewSheet);
}
yourNewSheet = ss.insertSheet();
yourNewSheet.setName(newNamer);
}
else {
Logger.log('No name provided ');
}
}
Spreadsheet Copy Content
Select active content and copy it. function myFun() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var data = sheet.getActiveRange().getValues();
Logger.log(data);
var newNamer = 'copied';
var yourNewSheet = ss.getSheetByName(newNamer);
if (yourNewSheet != null) {
ss.deleteSheet(yourNewSheet);
}
yourNewSheet = ss.insertSheet();
yourNewSheet.setName(newNamer);
data.forEach(function (row) {
yourNewSheet.appendRow(row);
});
}
Spreadsheet Data from Calendar
You can use Google sheets as a source for data
for other Google Suite of products.
function myFun() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('feed');
sheet.deleteRows(1, 100);
ss.appendRow(['Start', 'End', 'Date', 'Title', 'Location', 'Desc', 'Full']);
var startTime = new Date();
var endTime = new Date();
endTime.setDate(startTime.getDate() + 31);
var cal = CalendarApp.getDefaultCalendar();
var events = cal.getEvents(startTime, endTime);
if (events && events.length > 0) {
for (var x = 0; x < events.length; x++) {
var arr = [
Utilities.formatDate(events[x].getStartTime(), Session.getScriptTimeZone(),
'HH:mm')
, Utilities.formatDate(events[x].getEndTime(), Session.getScriptTimeZone(),
'HH:mm')
, Utilities.formatDate(events[x].getStartTime(), Session.getScriptTimeZone(),
'MMM dd yyyy')
, events[x].getTitle()
, events[x].getLocation()
, events[x].getDescription()
, events[x].getId()
]
sheet.appendRow(arr);
}
}
}
Congratulations on completing the course!
Thank you for your support
Check out more about JavaScript at MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript
Find out more about my courses at http://discoveryvip.com/
Course instructor : Laurence Svekis -
providing online training to over
500,000 students across hundreds of
courses and many platforms.

More Related Content

PPTX
Angular Js Advantages - Complete Reference
PDF
Angular 7 Firebase5 CRUD Operations with Reactive Forms
PPTX
Angular tutorial
PPTX
Training On Angular Js
PDF
AngularJS for Beginners
PPT
Chapter 09
PPTX
Angular kickstart slideshare
Angular Js Advantages - Complete Reference
Angular 7 Firebase5 CRUD Operations with Reactive Forms
Angular tutorial
Training On Angular Js
AngularJS for Beginners
Chapter 09
Angular kickstart slideshare

What's hot (20)

PPTX
Angularjs PPT
PDF
Angular js
PPTX
Angular Js Get Started - Complete Course
PPTX
Continuous Quality
PDF
Introduction to React for Frontend Developers
PDF
PDF
One Weekend With AngularJS
PDF
Web components are the future of the web - Take advantage of new web technolo...
PPTX
Angular js PPT
PDF
Angular material
PPTX
AngularJS Introduction (Talk given on Aug 5 2013)
PDF
Angular material tutorial
PPT
Java script
PPT
Java script
PDF
Fewd week4 slides
ODP
Devoxx 09 (Belgium)
PPTX
Java script Session No 1
PDF
Implementing auto complete using JQuery
PDF
Angular 2 - How we got here?
PDF
AngularJS 101
Angularjs PPT
Angular js
Angular Js Get Started - Complete Course
Continuous Quality
Introduction to React for Frontend Developers
One Weekend With AngularJS
Web components are the future of the web - Take advantage of new web technolo...
Angular js PPT
Angular material
AngularJS Introduction (Talk given on Aug 5 2013)
Angular material tutorial
Java script
Java script
Fewd week4 slides
Devoxx 09 (Belgium)
Java script Session No 1
Implementing auto complete using JQuery
Angular 2 - How we got here?
AngularJS 101
Ad

Similar to Google Apps Script for Beginners- Amazing Things with Code (20)

PDF
Extending Google Apps/Spreadsheet using Google Apps Script
PDF
Google: Drive, Documents and Apps Script - How to work efficiently and happily
PDF
Minimal Fuss Data Transformation Using Google Apps Scripts
PDF
Google Sheets Programming With Google Apps Script Michael Maguire
PDF
Google Apps Script: Accessing G Suite & other Google services with JavaScript
PPTX
Learn java script
PPSX
DIWE - Programming with JavaScript
PPT
Javascript
PPTX
Java script
PPTX
1-JAVA SCRIPT. servere-side applications vs client side applications
PDF
Enterprise workflow with Apps Script
PDF
full javascript Book by Abhishek singh.pdf
PPTX
javascript client side scripting la.pptx
PDF
Integrate Google Drive with Google Apps Script
PDF
JavaScript Getting Started
PDF
javascript-variablesanddatatypes-130218094831-phpapp01.pdf
PPSX
Javascript variables and datatypes
PPT
GAS Session
PPT
data-types-operators-datatypes-operators.ppt
PPTX
gdscWorkShopJavascriptintroductions.pptx
Extending Google Apps/Spreadsheet using Google Apps Script
Google: Drive, Documents and Apps Script - How to work efficiently and happily
Minimal Fuss Data Transformation Using Google Apps Scripts
Google Sheets Programming With Google Apps Script Michael Maguire
Google Apps Script: Accessing G Suite & other Google services with JavaScript
Learn java script
DIWE - Programming with JavaScript
Javascript
Java script
1-JAVA SCRIPT. servere-side applications vs client side applications
Enterprise workflow with Apps Script
full javascript Book by Abhishek singh.pdf
javascript client side scripting la.pptx
Integrate Google Drive with Google Apps Script
JavaScript Getting Started
javascript-variablesanddatatypes-130218094831-phpapp01.pdf
Javascript variables and datatypes
GAS Session
data-types-operators-datatypes-operators.ppt
gdscWorkShopJavascriptintroductions.pptx
Ad

More from Laurence Svekis ✔ (20)

PDF
Quiz JavaScript Objects Learn more about JavaScript
PDF
JavaScript Lessons 2023 V2
PDF
JavaScript Lessons 2023
PDF
Top 10 Linkedin Tips Guide 2023
PDF
JavaScript Interview Questions 2023
PDF
Code examples javascript ebook
PDF
Javascript projects Course
PDF
10 java script projects full source code
PDF
Chrome DevTools Introduction 2020 Web Developers Guide
PDF
Brackets code editor guide
PDF
Web hosting get start online
PDF
JavaScript guide 2020 Learn JavaScript
PDF
Web hosting Free Hosting
PDF
Web development resources brackets
PPTX
Local SQLite Database with Node for beginners
PDF
Introduction to Node js for beginners + game project
PPTX
JavaScript DOM - Dynamic interactive Code
PPTX
JavaScript Advanced - Useful methods to power up your code
PPTX
Monster JavaScript Course - 50+ projects and applications
PPTX
JavaScript Objects and OOP Programming with JavaScript
Quiz JavaScript Objects Learn more about JavaScript
JavaScript Lessons 2023 V2
JavaScript Lessons 2023
Top 10 Linkedin Tips Guide 2023
JavaScript Interview Questions 2023
Code examples javascript ebook
Javascript projects Course
10 java script projects full source code
Chrome DevTools Introduction 2020 Web Developers Guide
Brackets code editor guide
Web hosting get start online
JavaScript guide 2020 Learn JavaScript
Web hosting Free Hosting
Web development resources brackets
Local SQLite Database with Node for beginners
Introduction to Node js for beginners + game project
JavaScript DOM - Dynamic interactive Code
JavaScript Advanced - Useful methods to power up your code
Monster JavaScript Course - 50+ projects and applications
JavaScript Objects and OOP Programming with JavaScript

Recently uploaded (20)

PPTX
QR Codes Qr codecodecodecodecocodedecodecode
PDF
The Internet -By the Numbers, Sri Lanka Edition
PPTX
Introduction about ICD -10 and ICD11 on 5.8.25.pptx
PPTX
CHE NAA, , b,mn,mblblblbljb jb jlb ,j , ,C PPT.pptx
PPTX
INTERNET------BASICS-------UPDATED PPT PRESENTATION
PPTX
522797556-Unit-2-Temperature-measurement-1-1.pptx
PDF
Centralized Business Email Management_ How Admin Controls Boost Efficiency & ...
PDF
Best Practices for Testing and Debugging Shopify Third-Party API Integrations...
PPTX
innovation process that make everything different.pptx
PPTX
Digital Literacy And Online Safety on internet
PPTX
Internet___Basics___Styled_ presentation
PDF
Paper PDF World Game (s) Great Redesign.pdf
PDF
Automated vs Manual WooCommerce to Shopify Migration_ Pros & Cons.pdf
DOCX
Unit-3 cyber security network security of internet system
PDF
Vigrab.top – Online Tool for Downloading and Converting Social Media Videos a...
PDF
APNIC Update, presented at PHNOG 2025 by Shane Hermoso
PDF
LABUAN4D EXCLUSIVE SERVER STAR GAMING ASIA NO.1
PPTX
international classification of diseases ICD-10 review PPT.pptx
PDF
Behind the Smile Unmasking Ken Childs and the Quiet Trail of Deceit Left in H...
PDF
“Google Algorithm Updates in 2025 Guide”
QR Codes Qr codecodecodecodecocodedecodecode
The Internet -By the Numbers, Sri Lanka Edition
Introduction about ICD -10 and ICD11 on 5.8.25.pptx
CHE NAA, , b,mn,mblblblbljb jb jlb ,j , ,C PPT.pptx
INTERNET------BASICS-------UPDATED PPT PRESENTATION
522797556-Unit-2-Temperature-measurement-1-1.pptx
Centralized Business Email Management_ How Admin Controls Boost Efficiency & ...
Best Practices for Testing and Debugging Shopify Third-Party API Integrations...
innovation process that make everything different.pptx
Digital Literacy And Online Safety on internet
Internet___Basics___Styled_ presentation
Paper PDF World Game (s) Great Redesign.pdf
Automated vs Manual WooCommerce to Shopify Migration_ Pros & Cons.pdf
Unit-3 cyber security network security of internet system
Vigrab.top – Online Tool for Downloading and Converting Social Media Videos a...
APNIC Update, presented at PHNOG 2025 by Shane Hermoso
LABUAN4D EXCLUSIVE SERVER STAR GAMING ASIA NO.1
international classification of diseases ICD-10 review PPT.pptx
Behind the Smile Unmasking Ken Childs and the Quiet Trail of Deceit Left in H...
“Google Algorithm Updates in 2025 Guide”

Google Apps Script for Beginners- Amazing Things with Code

  • 1. Google Apps Scripts Power up your Google Suite Course Guide https://www.udemy.com/learn-google-apps-script
  • 2. INSTRUCTOR: LAURENCE SVEKIS Course instructor : Laurence Svekis - Over 300 courses in technology and web applications. - 20 years of JavaScript web programming experience - 500,000+ students across multiple platforms - Digital instructor since 2002 READY TO HELP YOU LEARN and ANSWER ANY questions you may have.
  • 3. Google Apps Scripts Course Guide This guide is designed to supplement the Google Apps Script It includes source code that follows the lessons of the course. One of the best ways to learn is to try the code out for yourself. Thanks for taking the course, if you have any questions or need clarification on the content please let me know in the Q&A section. Happy Coding …..
  • 4. Introduction to Google Apps Script https://developers.google.com/apps-script/ Increase the power of your favorite Google apps — like Calendar, Docs, Drive, Gmail, Sheets, and Slides. Apps Script is based on JavaScript 1.6, (1.7 and 1.8). Many basic JavaScript features in addition to the built-in and advanced Google services. Apps Script code runs on Google's servers (not client- side, except for HTML-service pages), browser- based features like DOM manipulation or the Window API are not available.
  • 5. Create a Script - Google Sheets To begin you must have a Google Account. 1. Log into your Google Account, create a new spreadsheet. https://docs.google.com/spreadsheets/u/0/ 2. Open blank sheet and give it a name 3. Add some random data with headings in first row.
  • 6. Create a Script - Marco 1. In the tools bar select marco. 2. Bold some of the cells in your sheet. 3. Change color of items in cells. 4. Record marco and give it a name 5. Select Edit Script at the bottom
  • 7. Edit a Script - Marco You can also access the script now under the tools tab and hit script editor. You will see the Marco you created in the Marcos menu. If you run the marco it will ask you for permissions.
  • 8. Edit a Script - Apps Script Editor - Try IT In the menu under tools click script editor Open the editor and you will open it in the online Apps Script IDE. Welcome to Google Apps Script. You will see code with a function named the same as the Marco. Inside is Google Apps Script. Make some changes SAVE and go back to the spreadsheet. Run the Marco, see what happens. function changetext() { var spreadsheet = SpreadsheetApp.getActive(); spreadsheet.getRange('A4:D6').activate(); spreadsheet.getActiveRangeList().setFontWeight('bold') .setFontColor('#0000ff'); }; CHANGED TO spreadsheet.getRange('A1:D6').activate(); spreadsheet.getActiveRangeList().setFontStyle('italic') .setFontColor('red');
  • 9. One More Marco…. Take two columns with numbers, record a macro adding the numbers and returning a sum in a new column. Open the script editor and update the + to *. Run the marco again. function adder() { var spreadsheet = SpreadsheetApp.getActive(); spreadsheet.getRange('G2').activate(); spreadsheet.getCurrentCell().setFormula('=SUM(E2+F2)'); spreadsheet.getActiveRange().autoFill(spreadsheet.getRange('G2:G7'), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES); spreadsheet.getRange('H7').activate(); }; CHANGE TO spreadsheet.getCurrentCell().setFormula('=SUM(E2*F2)');
  • 10. Run the App Script in the Editor Update the adder function adding at the end the code from the other marco, changing font color and style. Click Save and in the drop down select the adder function. Press the play/run button. function adder() { var spreadsheet = SpreadsheetApp.getActive(); spreadsheet.getRange('G2').activate(); spreadsheet.getCurrentCell().setFormula('=SUM(E2*F2)'); spreadsheet.getActiveRange().autoFill(spreadsheet.getRange('G2:G7'), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES); spreadsheet.getActiveRangeList().setFontStyle('italic') .setFontColor('blue'); };
  • 11. Apps Script Apps Script can - ● Write custom functions and macros for Google Sheets. ● Add custom menus, dialogs, and sidebars to Google Docs, Sheets, and Forms. ● Publish web apps — either standalone or embedded in Google Sites. ● Interact with other Google services, including AdSense, Analytics, Calendar, Drive, Gmail, and Maps. ● Build add-ons to extend Google Docs, Sheets, Slides, and Forms Two types of scripts Bound script and Standalone script. Currently we have created a bound script…. Let’s create a standalone script. Go to URL https://script.google.com/home Select New Script button
  • 12. Create Standalone Script Custom Functions Open online IDE editor. This is where you write scripts. 1. Add a name for your script. 2. Update the Code.gs myFunction with code. 3. Press the run button. 4. Accept permissions check your email! function myFunction() { var doc = DocumentApp.create('First Document'); doc.getBody().appendParagraph('Hello World'); var url = doc.getUrl(); var email = Session.getActiveUser().getEmail(); var subject = doc.getName(); var body = 'The document you just created : ' + url; GmailApp.sendEmail(email, subject, body); }
  • 13. Document ID https://developers.google.com/apps- script/reference/document/ Every Google document has a unique ID. Easiest way to get it is open the document and get it from the URL. Use getBody() method and appendParagraph() Try with JavaScript Method for Date(). function updater(){ var doc = DocumentApp.openById('15gBfW32K8wZleJC5DtYWeEGBm3CUbSQl7jBlh0ffZfM' ); doc.getBody().appendParagraph('Another Paragraph Just added'); var now = new Date(); doc.getBody().appendParagraph('Another Paragraph Just added at '+ now); }
  • 14. Document Service https://developers.google.com/apps- script/reference/document/ This service allows scripts to create, access, and modify Google Docs files. Each services has classes and methods in addition to allowable attributes. Use Logger.log to debug and get data in the log. Use Logger.log function docIDer() { var doc = DocumentApp.openById('15gBfW32K8wZleJC5DtYWeEGBm3CUbSQl7jBlh0ffZfM'); var id = doc.getId() Logger.log(id); }
  • 15. JavaScript in Google Apps Script. Google Apps Script is based on JavaScript, next few lessons will review core JavaScript fundamentals and how it relates to Apps Script. Apps Script is based on JavaScript 1.6, (1.7 and 1.8). Many basic JavaScript features in addition to the built-in and advanced Google services. Apps Script code runs on Google's servers (not client- side, except for HTML-service pages), browser- based features like DOM manipulation or the Window API are not available.
  • 16. JavaScript - Variables/Data Types The var statement declares a variable, optionally initializing it to a value. https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Statements/ var Variables are one of the most fundamental notions. Stores the value in memory and can be accessed later in the code using the variable. ● JavaScript is Case Sensitive ● camelCase when writing JavaScript variables ● Can’t use reserved words ● No Spaces in variable name ● Can’t start with digit only letter, $, or _ Use Logger.log function jsVar(){ var myString = "Hello World"; var myNumber = 10; var myBoolean = true; Logger.log(myNumber + myNumber); Logger.log(myString + ' ' + myNumber); Logger.log(typeof myBoolean); }
  • 17. JavaScript - Arrays Arrays and objects allow us to hold multiple values in the same variable. Can be used to make more complex data structures, all data types allowed within. https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Global_Objec ts/Array Arrays have built in methods that allow you to do manipulate the array and more. function jsMulti(){ var fruits = ['Apple', 'Banana','Orange','Pear']; Logger.log(fruits.length); fruits.forEach(function(item, index, array) { Logger.log(item, index); }); var addLast = fruits.push('Grape'); var removelast = fruits.pop(); var removeFirst = fruits.shift(); var addFirst = fruits.unshift('Peach'); var pos = fruits.indexOf('Banana'); Logger.log(pos); Logger.log(fruits); }
  • 18. JavaScript - Objects An object is a collection of related data and/or functionality (which usually consists of several variables and functions — which are called properties and methods when they are inside objects. https://developer.mozilla.org/en- US/docs/Learn/JavaScript/Objects/Basics function jsObject() { var car = { make: 'ford' , model: 'mustang' , year: 2000 , price: 50000 , color: 'red' , tires: true , drive: function () { Logger.log('its driving'); } , instructions: ['turn key', 'put in gear', 'press gas pedal', 'turn wheel as needed'] }; Logger.log(car); car.drive(); }
  • 19. JavaScript - Functions Functions are one of the fundamental building blocks in JavaScript. A function is a JavaScript procedure—a set of statements that performs a task or calculates a value. https://developer.mozilla.org/en- US/docs/Web/JavaScript/Guide/Functions We’ve been using functions throughout the lessons. Run a block of code. Function declarations load before any code is executed while Function expressions load only when the interpreter reaches that line of code. You can pass in values as arguments and have return within the function. function myFunction() { const message1 = function (mes) { Logger.log(mes); } message1('hello'); message1('welcome'); message1('bye bye'); function message2(mes) { Logger.log(mes); } message2('hello'); message2('welcome'); message2('bye bye'); function message3(mes) { return 'Great job on the ' + mes; } Logger.log(message3('code')); }
  • 20. JavaScript - Conditions The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement. https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Operators/C onditional_Operator The if statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement can be executed. https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Statements/i f...else function myCondition() { var age = 26; var beverage = (age >= 21) ? "Beer" : "Juice"; Logger.log(beverage); function testNum(a) { if (a > 0) { return "positive"; } else { return "NOT positive"; } } Logger.log(testNum(5)); Logger.log(testNum(-5)); }
  • 21. JavaScript - Loops and iteration Loops offer a quick and easy way to do something repeatedly. https://developer.mozilla.org/en- US/docs/Web/JavaScript/Guide/Loops_and_iterat ion function myLoops() { for (var step = 0; step < 5; step++) { Logger.log('Step #' + step); } var i = 0; do { i++; Logger.log('Counter ' + i); } while (i < 5); }
  • 22. IDE Online Editor File Tab Cloud based debugger for debugging App Scripts in the web browser. Same for both Bound scripts and Standalone scripts. ● Create a script file ● Create an HTML file call it index ● Open index and write some HTML code Under File tab you will find main project settings and able to create new files.
  • 23. IDE Online Editor Edit Tab ● Press Content assist you will see the content popup window. ● In your gs file create a function that outputs the current date in the Logger. ● Click Current Projects Triggers. In the new window press + Add Trigger - bottom right side ● Add trigger to project select function with time, Time-Driven, Minutes timer, Every minute and press save. Under Edit tab edit options like find and replace and content assist. Triggers. function whatisthetime() { var now = new Date(); Logger.log(now); }
  • 24. IDE Online Editor View Tab You can adjust your environment as well as see logs here. Under View tab Logs and control options.
  • 25. IDE Online Editor Run Tab ● Click on your code where the line numbers are, add the red dot. ● Select run and then the function ● Select debug and then the function. Notice the popup window at the bottom for debugger. Stops on red indicator allows you to debug your code. ● Press continue on the menu will run to next breakpoint if there is or complete. Under Run tab allows you to execute functions. function whatisthetime() { var now = new Date(); Logger.log(now); Logger.log(now); }
  • 26. IDE Online Editor Publish Tab Deploy your Google Web app, several options for deployment. ● Add code doGet() function ● Click Deploy as web app ● Click latest code - developer version ● Copy web app URL in your browser. ● Serve Page content from index file. https://developers.google.com/apps-script/guides/html/ Under Publish tab allows you to create web apps to publish. function doGet(){ var textOutput = ContentService.createTextOutput("Hello World!") return textOutput } function doGet() { return HtmlService.createHtmlOutputFromFile('index'); }
  • 27. Web App Dynamic Code Update your HTML index file code with <?= ?> This allows you to run Google Script directly in your client side. Update doGet() to include evaluate() method to run the code. Update who has access to the app, to allow others to see the app at the URL Use the same developer URL or publish a new version to your web app. Same URL with new version code. <!DOCTYPE html> <html> <head> <base target="_top"> </head> <body> <h1>Hello World</h1> <p>Just some HTML nothing to see here</p> <div>Current Date <?= new Date() ?>.</div> </body> </html> function doGet() { return HtmlService .createTemplateFromFile('index') .evaluate(); }
  • 28. IDE Online Editor Resources and Help Resources allows you to select existing libraries and bring in using Advanced Google Services. More advanced concepts than we are covering in this course. Shortcuts menu bar does all the common main menu stuff with the icons. Help Tab provides more info on Google Apps Script. <!DOCTYPE html> <html> <head> <base target="_top"> </head> <body> <h1>Hello World</h1> <p>Just some HTML nothing to see here</p> <div>Current Date <?= new Date() ?>.</div> </body> </html>
  • 29. Document Service https://developers.google.com/apps- script/reference/document/ This service allows scripts to create, access, and modify Google Docs files. Each services has classes and methods in addition to allowable attributes. getParagraphs() https://developers.google.com/apps- script/reference/document/body#getParagraphs( ) Retrieves all the Paragraphs contained in the section (including ListItems). Use Logger.log getText() getParagraphs() function paraUpdater() { var doc = DocumentApp.openById('[DOCID]'); var bodyElement = doc.getBody(); var allParagraphs = bodyElement.getParagraphs(); Logger.log(allParagraphs); for (var i = 0; i < allParagraphs.length; i++) { Logger.log(allParagraphs[i].getText()); } }
  • 30. Dialogs and custom UI buttons Create a new document, under tools tab select script editor. onOpen() runs by default when the doc opens. https://developers.google.com/apps-script/guides/menus Add menu item and create a simple function to ask a UI question. You need to refresh your document to see the new ui or run the onOpen() Code will send an email to you if you say yes. function onOpen() { DocumentApp.getUi().createMenu('Advanced').addItem('Create', 'myFun').addToUi(); } function myFun() { var ui = DocumentApp.getUi(); var result = ui.alert('Are you having fun?', 'Is the Course everything you expected', ui.ButtonSet.YES_NO); var result = ui.alert('Would you like an email sent to you', ui.ButtonSet.YES_NO); if (result == ui.Button.YES) { var recipient = Session.getActiveUser().getEmail(); GmailApp.sendEmail(recipient, 'You got this', 'Great job it worked from the Google Doc.'); ui.alert('Email sent to .' + recipient); } else { ui.alert('No email sent.'); } }
  • 31. Document as PDF The following code will create your document as a PDF on your drive and allow you to send to your email. Create the UI button and show the popup alert. Get users email Create file on gDrive Send the file in an email. Try the code below to see how you can convert your doc into a PDF store to your drive and send it in an email. function myFun() { var doc = DocumentApp.getActiveDocument(); var ui = DocumentApp.getUi(); var result = ui.alert('Would you like to save (Name:' + doc.getName() + '.pdf) as PDF?', ui.ButtonSet.YES_NO); if (result == ui.Button.YES) { var docblob = DocumentApp.getActiveDocument().getAs('application/pdf'); docblob.setName(doc.getName() + ".pdf"); var file = DriveApp.createFile(docblob); ui.alert('Your PDF file is available at ' + file.getUrl()); var recipient = Session.getActiveUser().getEmail(); var message = "Your new document is attached"; MailApp.sendEmail(recipient, 'PDF Doc', message, { name: 'New ' + doc.getName() + '.pdf created' , attachments: [file] }); } else { ui.alert('No PDF you cancelled.'); } }
  • 32. Spreadsheet Service https://developers.google.com/apps- script/reference/spreadsheet/ This service allows scripts to create, access, and modify Google Sheets files. Create a new spreadsheet, add a function that gets the sheet name. function myFunction() { var ss = SpreadsheetApp.getActiveSpreadsheet(); Logger.log(ss.getName()); var sheet = ss.getActiveSheet(); Logger.log(sheet.getName()); }
  • 33. Spreadsheet Data Add some content to your sheet. Lets get it in code. Get all the content and then get selected content from the active range. Notice the array format [] and then each row [] [[2.0, Joe, Smith, [email protected], 2.0], [3.0, Jane, Doe, [email protected], 3.0], [4.0, John, Doe, [email protected], 5.0]] function getContent(){ var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); var data1 = sheet.getDataRange().getValues(); Logger.log(data1); var data2 = sheet.getActiveRange().getValues(); Logger.log(data2); }
  • 34. Spreadsheet Add UI Create a new sheet dynamically. Add the menu UI option and invoke the function to ask for a new sheet by name. function onOpen() { SpreadsheetApp.getUi() .createMenu('Adv') .addItem('Update', 'myFun') .addToUi(); } function myFun() { var ui = SpreadsheetApp.getUi(); var ss = SpreadsheetApp.getActiveSpreadsheet(); var response = ui.prompt('Name of Sheet', 'Create name of sheet?', ui.ButtonSet.YES_NO); if (response.getSelectedButton() == ui.Button.YES) { var newNamer = response.getResponseText(); Logger.log('The new sheet name is %s.', newNamer); var yourNewSheet = ss.getSheetByName(newNamer); if (yourNewSheet != null) { ss.deleteSheet(yourNewSheet); } yourNewSheet = ss.insertSheet(); yourNewSheet.setName(newNamer); } else { Logger.log('No name provided '); } }
  • 35. Spreadsheet Copy Content Select active content and copy it. function myFun() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getActiveSheet(); var data = sheet.getActiveRange().getValues(); Logger.log(data); var newNamer = 'copied'; var yourNewSheet = ss.getSheetByName(newNamer); if (yourNewSheet != null) { ss.deleteSheet(yourNewSheet); } yourNewSheet = ss.insertSheet(); yourNewSheet.setName(newNamer); data.forEach(function (row) { yourNewSheet.appendRow(row); }); }
  • 36. Spreadsheet Data from Calendar You can use Google sheets as a source for data for other Google Suite of products. function myFun() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheetByName('feed'); sheet.deleteRows(1, 100); ss.appendRow(['Start', 'End', 'Date', 'Title', 'Location', 'Desc', 'Full']); var startTime = new Date(); var endTime = new Date(); endTime.setDate(startTime.getDate() + 31); var cal = CalendarApp.getDefaultCalendar(); var events = cal.getEvents(startTime, endTime); if (events && events.length > 0) { for (var x = 0; x < events.length; x++) { var arr = [ Utilities.formatDate(events[x].getStartTime(), Session.getScriptTimeZone(), 'HH:mm') , Utilities.formatDate(events[x].getEndTime(), Session.getScriptTimeZone(), 'HH:mm') , Utilities.formatDate(events[x].getStartTime(), Session.getScriptTimeZone(), 'MMM dd yyyy') , events[x].getTitle() , events[x].getLocation() , events[x].getDescription() , events[x].getId() ] sheet.appendRow(arr); } } }
  • 37. Congratulations on completing the course! Thank you for your support Check out more about JavaScript at MDN. https://developer.mozilla.org/en-US/docs/Web/JavaScript Find out more about my courses at http://discoveryvip.com/ Course instructor : Laurence Svekis - providing online training to over 500,000 students across hundreds of courses and many platforms.

Editor's Notes

  • #13: Create Standalone Script