Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
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, 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);
}
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.