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

What's hot (20)

PPTX
Angularjs PPT
Amit Baghel
 
PDF
Angular js
Knoldus Inc.
 
PPTX
Angular Js Get Started - Complete Course
EPAM Systems
 
PPTX
Continuous Quality
Stefano Galati
 
PDF
Introduction to React for Frontend Developers
Sergio Nakamura
 
PDF
AngularJS
Hiten Pratap Singh
 
PDF
One Weekend With AngularJS
Yashobanta Bai
 
PDF
Web components are the future of the web - Take advantage of new web technolo...
Marios Fakiolas
 
PPTX
Angular js PPT
Imtiyaz Ahmad Khan
 
PDF
Angular material
Kalpesh Satasiya
 
PPTX
AngularJS Introduction (Talk given on Aug 5 2013)
Abhishek Anand
 
PDF
Angular material tutorial
HarikaReddy115
 
PPT
Java script
umesh patil
 
PPT
Java script
umesh patil
 
PDF
Fewd week4 slides
William Myers
 
ODP
Devoxx 09 (Belgium)
Roger Kitain
 
PPTX
Java script Session No 1
Saif Ullah Dar
 
PDF
Implementing auto complete using JQuery
Bhushan Mulmule
 
PDF
Angular 2 - How we got here?
Marios Fakiolas
 
PDF
AngularJS 101
Houssem Yahiaoui
 
Angularjs PPT
Amit Baghel
 
Angular js
Knoldus Inc.
 
Angular Js Get Started - Complete Course
EPAM Systems
 
Continuous Quality
Stefano Galati
 
Introduction to React for Frontend Developers
Sergio Nakamura
 
One Weekend With AngularJS
Yashobanta Bai
 
Web components are the future of the web - Take advantage of new web technolo...
Marios Fakiolas
 
Angular js PPT
Imtiyaz Ahmad Khan
 
Angular material
Kalpesh Satasiya
 
AngularJS Introduction (Talk given on Aug 5 2013)
Abhishek Anand
 
Angular material tutorial
HarikaReddy115
 
Java script
umesh patil
 
Java script
umesh patil
 
Fewd week4 slides
William Myers
 
Devoxx 09 (Belgium)
Roger Kitain
 
Java script Session No 1
Saif Ullah Dar
 
Implementing auto complete using JQuery
Bhushan Mulmule
 
Angular 2 - How we got here?
Marios Fakiolas
 
AngularJS 101
Houssem Yahiaoui
 

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

PDF
Wordpress as a framework
Aggelos Synadakis
 
PPTX
Google Cloud Platform
Francesco Marchitelli
 
DOCX
ANGULAR JS LAB MANUAL(final) vtu2021 sch
kannikadg
 
PPTX
...and thus your forms automagically disappeared
Luc Bors
 
PPTX
Java script
Sadeek Mohammed
 
PDF
Progressive Web Application by Citytech
Ritwik Das
 
PDF
Google Apps Script: Accessing G Suite & other Google services with JavaScript
wesley chun
 
PPTX
Google App Engine for PHP
Eric Johnson
 
PDF
Angular js
Thyda Eng
 
PPTX
Wt unit 5
team11vgnt
 
PPTX
Android Development : (Android Studio, PHP, XML, MySQL)
Kavya Barnadhya Hazarika
 
PPTX
TulsaTechFest - Maximize SharePoint UX with free jQuery libraries
Mark Rackley
 
PDF
What I Learned At Drupal Con Dc 2009
Neil Giarratana
 
PPTX
React Basic and Advance || React Basic
rafaqathussainc077
 
PDF
HTML5 Up and Running
Codemotion
 
PPTX
phonegap with angular js for freshers
dssprakash
 
PDF
Iwt note(module 2)
SANTOSH RATH
 
PDF
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Doris Chen
 
PPTX
MongoDB.local Seattle 2019: MongoDB Stitch Tutorial
MongoDB
 
DOCX
Company Visitor Management System Report.docx
fantabulous2024
 
Wordpress as a framework
Aggelos Synadakis
 
Google Cloud Platform
Francesco Marchitelli
 
ANGULAR JS LAB MANUAL(final) vtu2021 sch
kannikadg
 
...and thus your forms automagically disappeared
Luc Bors
 
Java script
Sadeek Mohammed
 
Progressive Web Application by Citytech
Ritwik Das
 
Google Apps Script: Accessing G Suite & other Google services with JavaScript
wesley chun
 
Google App Engine for PHP
Eric Johnson
 
Angular js
Thyda Eng
 
Wt unit 5
team11vgnt
 
Android Development : (Android Studio, PHP, XML, MySQL)
Kavya Barnadhya Hazarika
 
TulsaTechFest - Maximize SharePoint UX with free jQuery libraries
Mark Rackley
 
What I Learned At Drupal Con Dc 2009
Neil Giarratana
 
React Basic and Advance || React Basic
rafaqathussainc077
 
HTML5 Up and Running
Codemotion
 
phonegap with angular js for freshers
dssprakash
 
Iwt note(module 2)
SANTOSH RATH
 
Develop High Performance Windows 8 Application with HTML5 and JavaScriptHigh ...
Doris Chen
 
MongoDB.local Seattle 2019: MongoDB Stitch Tutorial
MongoDB
 
Company Visitor Management System Report.docx
fantabulous2024
 
Ad

More from Laurence Svekis ✔ (20)

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

Recently uploaded (20)

DOCX
Custom vs. Off-the-Shelf Banking Software
KristenCarter35
 
PDF
BRKSP-2551 - Introduction to Segment Routing.pdf
fcesargonca
 
PDF
The Internet - By the numbers, presented at npNOG 11
APNIC
 
PDF
BRKACI-1003 ACI Brownfield Migration - Real World Experiences and Best Practi...
fcesargonca
 
PPTX
PHIPA-Compliant Web Hosting in Toronto: What Healthcare Providers Must Know
steve198109
 
PPTX
西班牙巴利阿里群岛大学电子版毕业证{UIBLetterUIB文凭证书}文凭复刻
Taqyea
 
PPTX
Networking_Essentials_version_3.0_-_Module_5.pptx
ryan622010
 
PPTX
Softuni - Psychology of entrepreneurship
Kalin Karakehayov
 
PDF
Enhancing Parental Roles in Protecting Children from Online Sexual Exploitati...
ICT Frame Magazine Pvt. Ltd.
 
PPTX
04 Output 1 Instruments & Tools (3).pptx
GEDYIONGebre
 
PDF
Digital burnout toolkit for youth workers and teachers
asociatiastart123
 
PDF
Top 10 Testing Procedures to Ensure Your Magento to Shopify Migration Success...
CartCoders
 
PPTX
Lec15_Mutability Immutability-converted.pptx
khanjahanzaib1
 
PPTX
Orchestrating things in Angular application
Peter Abraham
 
PDF
BRKAPP-1102 - Proactive Network and Application Monitoring.pdf
fcesargonca
 
PPTX
Networking_Essentials_version_3.0_-_Module_3.pptx
ryan622010
 
PDF
FutureCon Seattle 2025 Presentation Slides - You Had One Job
Suzanne Aldrich
 
PPTX
L1A Season 1 ENGLISH made by A hegy fixed
toszolder91
 
PPTX
Metaphysics_Presentation_With_Visuals.pptx
erikjohnsales1
 
PDF
Cleaning up your RPKI invalids, presented at PacNOG 35
APNIC
 
Custom vs. Off-the-Shelf Banking Software
KristenCarter35
 
BRKSP-2551 - Introduction to Segment Routing.pdf
fcesargonca
 
The Internet - By the numbers, presented at npNOG 11
APNIC
 
BRKACI-1003 ACI Brownfield Migration - Real World Experiences and Best Practi...
fcesargonca
 
PHIPA-Compliant Web Hosting in Toronto: What Healthcare Providers Must Know
steve198109
 
西班牙巴利阿里群岛大学电子版毕业证{UIBLetterUIB文凭证书}文凭复刻
Taqyea
 
Networking_Essentials_version_3.0_-_Module_5.pptx
ryan622010
 
Softuni - Psychology of entrepreneurship
Kalin Karakehayov
 
Enhancing Parental Roles in Protecting Children from Online Sexual Exploitati...
ICT Frame Magazine Pvt. Ltd.
 
04 Output 1 Instruments & Tools (3).pptx
GEDYIONGebre
 
Digital burnout toolkit for youth workers and teachers
asociatiastart123
 
Top 10 Testing Procedures to Ensure Your Magento to Shopify Migration Success...
CartCoders
 
Lec15_Mutability Immutability-converted.pptx
khanjahanzaib1
 
Orchestrating things in Angular application
Peter Abraham
 
BRKAPP-1102 - Proactive Network and Application Monitoring.pdf
fcesargonca
 
Networking_Essentials_version_3.0_-_Module_3.pptx
ryan622010
 
FutureCon Seattle 2025 Presentation Slides - You Had One Job
Suzanne Aldrich
 
L1A Season 1 ENGLISH made by A hegy fixed
toszolder91
 
Metaphysics_Presentation_With_Visuals.pptx
erikjohnsales1
 
Cleaning up your RPKI invalids, presented at PacNOG 35
APNIC
 

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