0% found this document useful (0 votes)
2 views26 pages

Apps Script Code Snippets V2

Uploaded by

yiyimip426
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views26 pages

Apps Script Code Snippets V2

Uploaded by

yiyimip426
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

1

Apps Script Coding Examples

Creating a Google Calendar Event 2


Extracting Data from a Google Form 3
Creating a Google Slides Presentation 4
Using Google Translate API 5
Copying a Google Drive Folder 6
Adding a Custom Menu to a Google Sheet 7
Converting a Google Sheet to PDF 8
Setting a Google Sheet's Cell Value 9
Uploading a File to Google Drive 10
Sending an Email from Google Sheets 11
Sending Emails 11
Creating a Calendar Event 12
Creating a Google Form 12
Reading Data from Google Sheets 13
Writing Data to Google Sheets 14

Laurence Svekis [Link]


2

Send Emails Automatically: 14


Custom Emails and HTML option 15
Create Google Forms: 16
Creating a custom form 17
Generate Google Docs: 20
Create and update a Google Doc 20
Add Data to Google Sheets: 23
Create and update a Google Sheet 23
Automate Google Calendar: 25
Add new event to Default Calendar 25

Creating a Google Calendar Event


This example shows how to create a new event on a Google
Calendar using Google Apps Script.
function createCalendarEvent() {
var calendarId = "your_calendar_id";
var calendar =
[Link](calendarId);
var event = [Link]('Test Event', new
Date('March 10, 2023 [Link]'), new Date('March 10,
2023 [Link]'));
}
Explanation:
In this script, we first define the calendar ID of the Google
Calendar we want to create the event on. We then call the
[Link]() function to get the calendar with
the specified ID. We then create a new event on the calendar

Laurence Svekis [Link]


3

using the createEvent() function and passing the event title, start
date, and end date as arguments.

Extracting Data from a Google Form


This example shows how to extract data from a Google Form
using Google Apps Script.
function extractFormData() {
var formId = "your_form_id";
var form = [Link](formId);
var responses = [Link]();
for (var i = 0; i < [Link]; i++) {
var response = responses[i];
var itemResponses = [Link]();
for (var j = 0; j < [Link]; j++) {
var itemResponse = itemResponses[j];
var question = [Link]().getTitle();
var answer = [Link]();
[Link]("Question: " + question + ", Answer: "
+ answer);
}
}
}
Explanation:

Laurence Svekis [Link]


4

In this script, we first define the form ID of the Google Form we


want to extract data from. We then call the [Link]()
function to open the form with the specified ID. We then get all
the form responses using the getResponses() function and loop
through each response. For each response, we get the item
responses using the getItemResponses() function and loop
through each item response. We then get the question and
answer for each item response using the getTitle() and
getResponse() functions and log them to the console.

Creating a Google Slides Presentation


This example shows how to create a new presentation on Google
Slides using Google Apps Script.
function createPresentation() {
var presentationTitle = "Test Presentation";
var presentation =
[Link](presentationTitle);
var slide = [Link]()[0];
[Link]([Link], 0,
0, 100, 100);
}
Explanation:
In this script, we first define the title of the new presentation we
want to create. We then call the [Link]() function to

Laurence Svekis [Link]


5

create a new presentation with the specified title. We then get the
first slide of the presentation using the getSlides() function and
insert a rectangle shape on the slide using the insertShape()
function.

Using Google Translate API


This example shows how to use the Google Translate API to
translate text using Google Apps Script.
function translateText() {
var textToTranslate = "Hello World!";
var targetLanguage = "es";
var translatedText =
[Link](textToTranslate, '',
targetLanguage);
[Link]("Translated Text: " + translatedText);
}
Explanation:
In this script, we first define the text we want to translate and the
target language we want to translate the text into. We then call
the [Link]() function to translate the text using
the Google Translate API and passing the text, source language,
and target language as arguments. We then log the translated
text to the console using the [Link]() function.

Laurence Svekis [Link]


6

Copying a Google Drive Folder


This example shows how to copy a Google Drive folder using
Google Apps Script.
function copyFolder() {
var folderId = "your_folder_id";
var folder = [Link](folderId);
var newFolderName = [Link]() + " - Copy";
var newFolder = [Link](newFolderName);
var files = [Link]();
while ([Link]()) {
var file = [Link]();
[Link]([Link](), newFolder);
}
}
Explanation:
In this script, we first define the folder ID of the Google Drive
folder we want to copy. We then call the [Link]()
function to get the folder with the specified ID. We then create a
new folder with the same name as the original folder but with " -
Copy" appended to it using the [Link]() function.
We then get all the files in the original folder using the getFiles()
function and loop through each file. For each file, we make a copy
of the file in the new folder using the makeCopy() function and
passing the file name and the new folder as arguments.

Laurence Svekis [Link]


7

Adding a Custom Menu to a Google Sheet


This example shows how to add a custom menu to a Google
Sheet using Google Apps Script.
function onOpen() {
var ui = [Link]();
[Link]('Custom Menu')
.addItem('First Item', 'menuItem1')
.addSeparator()
.addItem('Second Item', 'menuItem2')
.addToUi();
}

function menuItem1() {
// Do something for the first menu item
}

function menuItem2() {
// Do something for the second menu item
}
Explanation:
In this script, we first define the onOpen() function, which is a
special function that runs automatically when the Google Sheet is

Laurence Svekis [Link]


8

opened. We then use the [Link]() function to get


the UI service for the Google Sheet. We then create a new
custom menu using the createMenu() function and add two menu
items using the addItem() function. We then define the two menu
item functions menuItem1() and menuItem2() which will be
executed when the corresponding menu item is clicked.

Converting a Google Sheet to PDF


This example shows how to convert a Google Sheet to PDF using
Google Apps Script.
function convertToPDF() {
var sheetId = "your_sheet_id";
var sheet =
[Link](sheetId).getSheetByName("Sheet1
");
var blob =
[Link]().getAs("application/pdf").setName("Sheet
[Link]");
[Link](blob);
}
Explanation:
In this script, we first define the sheet ID of the Google Sheet we
want to convert to PDF. We then call the

Laurence Svekis [Link]


9

[Link]() function to open the sheet with the


specified ID. We then get the sheet with the name "Sheet1" using
the getSheetByName() function. We then get the sheet data as a
PDF blob using the getBlob() and getAs() functions. We then
create a new file in Google Drive using the [Link]()
function.

Setting a Google Sheet's Cell Value


This example shows how to set a cell value in a Google Sheet
using Google Apps Script.
function setCellValue() {
var sheetId = "your_sheet_id";
var sheet =
[Link](sheetId).getSheetByName("Sheet1
");
[Link]("A1").setValue("Hello World!");
}
Explanation:
In this script, we first define the sheet ID of the Google Sheet we
want to set the cell value for. We then call the
[Link]() function to open the sheet with the
specified ID. We then get the sheet with the name "Sheet1" using
the getSheetByName() function. We then set the value of cell A1
to "Hello World!" using the setValue() function.

Laurence Svekis [Link]


10

Uploading a File to Google Drive


This example shows how to upload a file to Google Drive using
Google Apps Script.
function uploadFile() {
var file = [Link]("Test File", "This is
a test file");
var folderId = "your_folder_id";
var folder = [Link](folderId);
[Link](file);
}
Explanation:
In this script, we first create a new file in Google Drive using the
[Link]() function. We then define the folder ID of the
Google Drive folder we want to upload the file to. We then get the
folder with the specified ID using the [Link]()
function. We then add the newly created file to the folder using
the addFile() function.

Sending an Email from Google Sheets


This example shows how to send an email from a Google Sheet
using Google Apps Script.

Laurence Svekis [Link]


11

function sendEmail() {
var emailAddress = "recipient@[Link]";
var subject = "Test Email";
var body = "This is a test email";
[Link](emailAddress, subject, body);
}
Explanation:
In this script, we first define the recipient email address, subject,
and body of the email we want to send. We then call the
[Link]() function to send the email to the specified
recipient with the specified subject and body. Note that this
function requires the necessary authorization to be granted in
order to send emails.

Sending Emails
Google Apps Script can be used to send emails directly from
Google Sheets, Docs, or Forms. This is useful when you need to
send automated emails to a large number of recipients or when
you need to customize the content of the email for each recipient.
Here's an example code:
function sendEmail() {
var recipient = "example@[Link]";

Laurence Svekis [Link]


12

var subject = "Test Email";


var body = "This is a test email.";
[Link](recipient, subject, body);
}

Creating a Calendar Event


Google Apps Script can also be used to create calendar events
directly from Google Sheets or Forms. Here's an example code:
function createEvent() {
var calendar = [Link]();
var title = "Test Event";
var start = new Date("2023-03-05T[Link]Z");
var end = new Date("2023-03-05T[Link]Z");
[Link](title, start, end);
}

Creating a Google Form


Google Apps Script can be used to create Google Forms
programmatically. This is useful when you need to create a large
number of forms or when you need to customize the content of
the form for each respondent. Here's an example code:
function createForm() {
var form = [Link]("Test Form");
[Link]().setTitle("What is your name?");

Laurence Svekis [Link]


13

[Link]()
.setTitle("What is your favorite color?")
.setChoices([
[Link]("Red"),
[Link]("Blue"),
[Link]("Green"),
]);
}

Reading Data from Google Sheets


Google Apps Script can be used to read data from Google Sheets
and process it programmatically. Here's an example code that
reads the values from the first row of a sheet:
function readData() {
var sheet = [Link]();
var values = [Link]("1:1").getValues()[0];
[Link](values);
}

Writing Data to Google Sheets


Google Apps Script can also be used to write data to Google
Sheets. Here's an example code that writes the values "John" and
"Doe" to the first row of a sheet:
function writeData() {

Laurence Svekis [Link]


14

var sheet = [Link]();


[Link]("A1:B1").setValues([["John", "Doe"]]);
}

Send Emails Automatically:


With Apps Script, you can write a script that sends an email
automatically to a recipient or a group of recipients at a specific
time or interval. The code below sends an email message
containing a subject and a body to a specified email address.

function sendEmail() {
var recipient = "recipient@[Link]";
var subject = "Hello from Apps Script";
var body = "This email was sent using Google Apps
Script!";
[Link](recipient, subject, body);
}

Custom Emails and HTML option

function senderEmail(){
const email = [Link]().getEmail();

Laurence Svekis [Link]


15

const emailSend = 'gappscourses@[Link]';


const subject = 'Hello World';
const body = '<h1>Laurence Svekis</h1>';
[Link]({
to:email,
subject:subject,
htmlBody:body});
[Link](email);
}
const email = [Link]().getEmail(); - This line gets
the email address of the currently active user using the
[Link]() method and stores it in the email
constant. The getEmail() method retrieves the email address
associated with the user's account.

const emailSend = 'gappscourses@[Link]'; - This line defines


a constant variable named emailSend that contains the email
address of the recipient.

const subject = 'Hello World'; - This line defines a constant


variable named subject that contains the subject of the email
message.

Laurence Svekis [Link]


16

const body = '<h1>Laurence Svekis</h1>'; - This line defines a


constant variable named body that contains the body of the email
message. It is in HTML format.

[Link]({to:email, subject:subject, htmlBody:body});


- This line uses the MailApp service to send an email message to
the email address stored in the email constant. The email
message contains the subject stored in the subject constant and
the body stored in the body constant. The htmlBody option
specifies that the body of the message is in HTML format.

[Link](email); - This line logs the email address of the


currently active user to the execution log using the [Link]()
method.

Create Google Forms:


Google Forms is a powerful tool for collecting data from users.
With Apps Script, you can programmatically create Google Forms,
customize them, and collect the responses. The code below
creates a new Google Form and adds a multiple-choice question
with two options.

function createForm() {
var form = [Link]("My Form");

Laurence Svekis [Link]


17

var item = [Link]();


[Link]("Choose an option")
.setChoices([
[Link]("Option 1"),
[Link]("Option 2")
]);
}

Creating a custom form

function creatorForm(){
const form = [Link]('Laurence Svekis');
const item = [Link]();
[Link]('Select One')
.setChoices([
[Link]('One'),
[Link]('Two'),
[Link]('Three')
]);
}
The creatorForm() function creates a Google Form and adds a
multiple choice question to it. Here is a line-by-line explanation of
the code:

Laurence Svekis [Link]


18

const form = [Link]('Laurence Svekis'); - This line


creates a new Google Form with the title "Laurence Svekis" using
the [Link]() method. The create() method returns a
Form object that represents the newly created form.

const item = [Link](); - This line adds a


multiple choice question to the form using the
addMultipleChoiceItem() method of the Form object. The
addMultipleChoiceItem() method returns a MultipleChoiceItem
object that represents the newly created question.

[Link]('Select One') - This line sets the title of the multiple


choice question to "Select One" using the setTitle() method of the
MultipleChoiceItem object.

.setChoices([ - This line begins an array of answer choices for the


multiple choice question using the setChoices() method of the
MultipleChoiceItem object. The setChoices() method takes an
array of Choice objects as its argument.

[Link]('One'), - This line creates a new answer choice


with the text "One" using the createChoice() method of the
MultipleChoiceItem object. The createChoice() method returns a
Choice object that represents the newly created answer choice.

Laurence Svekis [Link]


19

[Link]('Two'), - This line creates a new answer choice


with the text "Two" using the createChoice() method of the
MultipleChoiceItem object.

[Link]('Three') - This line creates a new answer


choice with the text "Three" using the createChoice() method of
the MultipleChoiceItem object.

]); - This line ends the array of answer choices for the multiple
choice question using the setChoices() method of the
MultipleChoiceItem object.

After executing the creatorForm() function, a new Google Form


titled "Laurence Svekis" will be created with a multiple choice
question that has three answer choices: "One", "Two", and
"Three".

Generate Google Docs:


Google Docs is a cloud-based word processing tool that allows
users to create and edit documents. With Apps Script, you can
programmatically generate Google Docs, populate them with
data, and format them. The code below creates a new Google Doc
and adds a paragraph of text.

Laurence Svekis [Link]


20

function createDoc() {
var doc = [Link]("My Doc");
var body = [Link]();
[Link](0, "Hello from Apps Script!");
}

Create and update a Google Doc

function createmyDoc(){
const doc = [Link]('Laurence Svekis');
const body = [Link]();
[Link](0,'My new Doc, Laurence
Svekis');
}

function updatemyDoc(){
const id = '1JJyHruUbZQv4Q5zLHTVebDDbs';
const doc = [Link](id);
const body = [Link]();
[Link](10,'*****Laurence Svekis');
}

Laurence Svekis [Link]


21

The createmyDoc() function and the updatemyDoc() function


both manipulate a Google Docs document. Here's what each
function does:

createmyDoc(): This function creates a new Google Docs


document titled "Laurence Svekis", inserts a paragraph into the
document, and sets the text of the paragraph to "My new Doc,
Laurence Svekis". Here's what each line of the function does:
● const doc = [Link]('Laurence Svekis');: This
line creates a new Google Docs document titled "Laurence
Svekis" using the create() method of the DocumentApp
class. The create() method returns a Document object that
represents the newly created document.
● const body = [Link]();: This line gets the Body object
of the newly created document using the getBody() method
of the Document object.
● [Link](0,'My new Doc, Laurence Svekis');:
This line inserts a new paragraph at the beginning of the
document using the insertParagraph() method of the Body
object. The insertParagraph() method takes two arguments:
the position where the new paragraph should be inserted (in
this case, the beginning of the document), and the text of
the paragraph ("My new Doc, Laurence Svekis" in this case).

Laurence Svekis [Link]


22

updatemyDoc(): This function updates an existing Google Docs


document by inserting a new paragraph into it. Here's what each
line of the function does:
● const id = '1JJyHruUbZQv5LHTVebDDbs';: This line sets the
id variable to the ID of the Google Docs document that we
want to update. This ID is a unique identifier that is assigned
to each Google Docs document.
● const doc = [Link](id);: This line opens
the Google Docs document with the specified ID using the
openById() method of the DocumentApp class. The
openById() method returns a Document object that
represents the opened document.
● const body = [Link]();: This line gets the Body object
of the opened document using the getBody() method of the
Document object.
● [Link](10,'*****Laurence Svekis');: This line
inserts a new paragraph at position 10 (i.e., after the tenth
paragraph) in the document using the insertParagraph()
method of the Body object. The text of the new paragraph is
"*****Laurence Svekis". The insertParagraph() method
takes two arguments: the position where the new paragraph
should be inserted (in this case, after the tenth paragraph),
and the text of the paragraph ("*****Laurence Svekis" in
this case).

Laurence Svekis [Link]


23

Add Data to Google Sheets:


Google Sheets is a cloud-based spreadsheet tool that allows users
to create and edit spreadsheets. With Apps Script, you can
programmatically add data to a Google Sheet, retrieve data from
it, and perform various operations. The code below adds a new
row of data to a Google Sheet.

function addData() {
var sheet = [Link]();
[Link](["John Doe", "johndoe@[Link]",
"555-1234"]);
}

Create and update a Google Sheet

function makeSheets(){
const ss = [Link]('Laurence Sheet');
const sheet = [Link]()[0];
const row = ['Laurence','Svekis','100'];
[Link](row);
[Link]([Link]());
}

Laurence Svekis [Link]


24

function updateSheet(){
const id =
'1P9R_b-dTdoBAAWAGF6kPZyKSXJ6r2P_LFgrKeReNmrY';
const ss = [Link](id);
const sheet = [Link]()[0];
const row = ['1 Laurence','1 Svekis','55'];
[Link](row);
}

The first function makeSheets() creates a new Google Sheets file


with the name "Laurence Sheet" and then retrieves the first sheet
in the file. It then creates a new row containing three values,
'Laurence', 'Svekis', and '100', and appends the row to the end of
the sheet. Finally, it logs the ID of the created spreadsheet using
the Logger class.

The second function updateSheet() opens an existing Google


Sheets file using its ID and retrieves the first sheet in the file. It
then creates a new row containing three values, '1 Laurence', '1
Svekis', and '55', and appends the row to the end of the sheet.
The function updates the sheet in the file without creating a new
sheet.

Laurence Svekis [Link]


25

Automate Google Calendar:


Google Calendar is a powerful tool for managing events and
schedules. With Apps Script, you can automate various tasks in
Google Calendar, such as creating events, updating events, and
sending notifications. The code below creates a new event in
Google Calendar.

function createEvent() {
var calendar = [Link]();
var title = "My Event";
var start = new Date("March 1, 2023 [Link]");
var end = new Date("March 1, 2023 [Link]");
var event = [Link](title, start, end);
}

Add new event to Default Calendar

function myEventCal(){
const cal = [Link]();
const title = 'My Birthday';
const start = new Date('March 1, 2023 [Link]');
const end = new Date('March 1, 2023 [Link]');
const event = [Link](title,start,end);

Laurence Svekis [Link]


26

The function myEventCal() creates a new calendar event on the


default calendar of the user. First, it retrieves the default calendar
object using the getDefaultCalendar() method. Then, it creates
variables for the title of the event, the start time, and the end
time. In this case, the title of the event is "My Birthday", the start
time is set for March 1, 2023, at 10:00 AM, and the end time is
set for March 1, 2023, at 11:00 AM.

Finally, the createEvent() method is called on the cal object,


passing in the title, start, and end variables to create a new event
on the default calendar. The newly created event will be visible on
the user's calendar at the specified start and end times with the
specified title.

Laurence Svekis [Link]

You might also like