100+Apps+Script+Common+Code+Examples
100+Apps+Script+Common+Code+Examples
Snippets
1
Reading and Writing Data to Google Sheets 6
Sending Emails via Gmail 6
Creating Custom Menus in Google Sheets 6
Setting Up Triggers 7
Fetching Data from URLs (UrlFetchApp) 7
Parsing and Manipulating JSON Data 7
Creating and Managing Google Calendar Events 7
Sending Emails with Attachments 8
Working with Google Drive Files and Folders 8
Creating Dialogs and Sidebars 8
Batch Operations to Improve Performance 8
Manipulating Cell Formatting 9
Creating Web Apps with Google Apps Script 9
Importing Data from External Sources 9
Using Logger for Debugging 9
Copying Data Between Sheets 10
Converting Google Docs to PDF 10
Working with Form Responses 10
Error Handling in Apps Script 11
Creating Charts in Google Sheets 11
Appending Data to Google Sheets 11
Sorting Data in a Sheet 11
Filtering Data in a Sheet 12
Protecting Sheets or Ranges 12
Sending Emails with Inline Images 12
Creating and Managing Google Docs 13
Creating and Managing Google Slides 13
Generating PDFs from Google Sheets 13
Creating Custom Functions for Google Sheets 13
Working with Named Ranges 14
Using SpreadsheetApp.flush() 14
Formatting Numbers and Dates in Sheets 14
Using onEdit Triggers 14
Sending Notifications 15
Reading Data from Another Spreadsheet 15
2
Creating Forms Programmatically 15
Updating Charts 16
Moving or Renaming Files in Drive 16
Setting Cell Validation 16
Creating and Updating Pivot Tables 16
Using PropertiesService 17
Parsing XML Data 17
Adding Custom Images to Sheets 17
Hiding and Showing Sheets or Rows 18
Conditional Formatting 18
Importing Data from Another Spreadsheet 18
Interacting with Google Maps 19
Using Session Service 19
Using JDBC to Connect to External Databases 19
Using OAuth for External APIs 20
Translating Text Using LanguageApp 20
Performing Calculations in Scripts 21
Using Utilities.sleep() 21
Converting Currencies 21
Sending Calendar Invites 21
Creating Add-ons 22
Using Google Analytics API 22
Implementing RESTful APIs 22
Customizing the Editor UI 23
Migrating from VBA to Apps Script 23
Interacting with Other Google Cloud Services 23
Sending Push Notifications 24
Integrating with Slack 24
Implementing Pagination 25
Reading Email Attachments 25
Setting Time Zones 25
Copying a Spreadsheet 26
Setting Up Webhooks 26
Integrating with Third-Party APIs 26
Automating Data Backups 26
Encrypting Data 27
Using the Advanced Drive Service 27
3
Using the Advanced Sheets Service 27
Implementing OAuth2 Authentication 28
Parsing HTML Content 28
Error Logging to a Spreadsheet 29
Version Control with Apps Script 29
Using the ContentService for JSON Responses 29
Setting Up CORS in Web Apps 29
Implementing Authentication in Web Apps 30
Using the YouTube API 30
Using Cloud SQL 30
Processing Large Datasets Efficiently 31
Implementing Multi-Step Workflows 31
Interacting with Google Photos API 31
Using the Vision API 32
Using Machine Learning APIs 32
Using the Advanced Gmail Service 32
Implementing a Custom Sidebar 32
Creating Custom Charts 33
Using HTML Templates 33
Working with Google Slides 33
Using Regular Expressions 34
Sending Calendar Invites via Email 34
Generating PDFs from Sheets 34
Adding Notes to Cells 34
Protecting Ranges and Sheets 35
Creating Filters and Filter Views 35
Adding Conditional Formatting 35
Retrieving User Information 36
Formatting Dates and Times 36
Creating Custom HTML Dialogs 36
Appending Rows to Sheets 36
Deleting Rows or Columns 37
Hiding and Unhiding Sheets 37
Sending Slack Notifications 37
Creating and Deleting Drive Files 38
Exporting Sheets to Excel 38
Using the Properties Service 38
4
Creating Google Forms Programmatically 38
Using Spreadsheet Formulas via Apps Script 39
Sending Emails Based on Sheet Data 39
Manipulating Pivot Tables 39
Integrating with External APIs 39
Creating Drop-down Lists in Cells 40
Importing XML Data 40
Scheduling Functions with Time-driven Triggers 40
Parsing CSV Files from Drive 41
Sorting Data in Sheets 41
Using Cache Service 41
Adding Images to Sheets 41
Using Lock Service 42
Getting Spreadsheet Metadata 42
Sending SMS via Twilio API 42
Creating Nested Folders in Drive 43
Uninstalling Triggers 43
Checking for Empty Cells 43
Copying Files in Drive 44
Sending Emails with HTML Content 44
Creating Google Docs from Templates 44
Handling Form Submit Events 45
Generating Random Numbers and Strings 45
Using Advanced Google Services 45
Working with Date and Time 45
Using SpreadsheetApp.getUi() for Alerts 46
Creating Buttons in Sheets 46
Clearing Contents of a Range 46
Protecting Sheets with Passwords 46
Using SpreadsheetApp.openByUrl() 47
5
Whether you’re a beginner or a seasoned developer, this book offers a wide range of
examples to fit your needs. You’ll explore a variety of solutions, from automating
repetitive tasks to creating custom functions, building user interfaces, integrating with
APIs, and much more. Each example is crafted to be directly usable, making it easy to
incorporate into your projects or customize for specific needs.
Apps Script has opened new doors in automation, bridging the gap between productivity
and coding. This book aims to make this process accessible, practical, and, most
importantly, efficient. So dive in, experiment, and see how each example can transform
the way you work with Google Workspace!
6
Setting Up Triggers
Create a time-based trigger to run a function every hour.
function createTimeTrigger() {
ScriptApp.newTrigger('myFunction')
.timeBased()
.everyHours(1)
.create();
}
7
Sending Emails with Attachments
Send an email with a file attachment from Google Drive.
function sendEmailWithAttachment() {
var file = DriveApp.getFileById('FILE_ID');
MailApp.sendEmail({
to: '[email protected]',
subject: 'Subject',
body: 'Email body text',
attachments: [file.getAs(MimeType.PDF)]
});
}
8
sheet.getRange(1, 1, 2, 2).setValues(data);
}
9
Copying Data Between Sheets
Copy data from one sheet to another within the same spreadsheet.
function copySheetData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourceSheet = ss.getSheetByName('Sheet1');
var targetSheet = ss.getSheetByName('Sheet2');
var data = sourceSheet.getDataRange().getValues();
targetSheet.getRange(1, 1, data.length, data[0].length).setValues(data);
}
10
Error Handling in Apps Script
Use try-catch blocks to handle errors gracefully.
function errorHandling() {
try {
// Code that might throw an error
var result = someFunction();
} catch (e) {
Logger.log('An error occurred: ' + e.message);
}
}
11
}
12
}
13
function DOUBLE(number) {
return number * 2;
}
Using SpreadsheetApp.flush()
Ensure that pending changes are applied immediately.
function flushChanges() {
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange('A1').setValue('Processing...');
SpreadsheetApp.flush();
// Perform time-consuming operations
sheet.getRange('A1').setValue('Done');
}
14
if (range.getA1Notation() == 'A1') {
SpreadsheetApp.getActiveSheet().getRange('B1').setValue('A1 was edited');
}
}
Sending Notifications
Send an email notification when a condition is met.
function sendNotification() {
var sheet = SpreadsheetApp.getActiveSheet();
var value = sheet.getRange('A1').getValue();
if (value > 100) {
MailApp.sendEmail('[email protected]', 'Value Exceeded', 'The value in A1 is
over 100.');
}
}
15
Updating Charts
Refresh charts after data changes.
function refreshCharts() {
var sheet = SpreadsheetApp.getActiveSheet();
var charts = sheet.getCharts();
charts.forEach(function(chart) {
sheet.updateChart(chart);
});
}
16
var sheet = SpreadsheetApp.getActiveSheet();
var pivotTableParams = {
source: sheet.getRange('A1:C10'),
rows: [{ sourceColumnOffset: 0, showTotals: true }],
columns: [{ sourceColumnOffset: 1, showTotals: true }],
values: [{ summarizeFunction: 'SUM', sourceColumnOffset: 2 }]
};
sheet.addPivotTable(pivotTableParams);
}
Using PropertiesService
Store and retrieve script properties.
function propertiesExample() {
var properties = PropertiesService.getScriptProperties();
properties.setProperty('key', 'value');
var value = properties.getProperty('key');
Logger.log(value);
}
17
}
Conditional Formatting
Apply conditional formatting to a range.
function setConditionalFormatting() {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange('A1:A10');
var rule = SpreadsheetApp.newConditionalFormatRule()
.whenNumberGreaterThan(100)
.setBackground('red')
.setRanges([range])
.build();
var rules = sheet.getConditionalFormatRules();
rules.push(rule);
sheet.setConditionalFormatRules(rules);
}
18
Interacting with Google Maps
Get the distance between two locations.
function getDistance() {
var origin = 'New York, NY';
var destination = 'Los Angeles, CA';
var directions = Maps.newDirectionFinder()
.setOrigin(origin)
.setDestination(destination)
.getDirections();
var distance = directions.routes[0].legs[0].distance.text;
Logger.log('Distance: ' + distance);
}
19
}
20
Performing Calculations in Scripts
Compute mathematical operations and write results to a sheet.
function calculate() {
var sheet = SpreadsheetApp.getActiveSheet();
var a = 5;
var b = 10;
var sum = a + b;
sheet.getRange('A1').setValue(sum);
}
Using Utilities.sleep()
Pause script execution for a specified time.
function pauseExecution() {
Logger.log('Start');
Utilities.sleep(5000); // Sleep for 5 seconds
Logger.log('End');
}
Converting Currencies
Fetch current exchange rates and convert currencies.
function convertCurrency() {
var amount = 100;
var from = 'USD';
var to = 'EUR';
var rate = FinanceApp.getExchangeRate(from + to);
var converted = amount * rate;
Logger.log(converted);
}
21
sendInvites: true
});
}
Creating Add-ons
Set up a basic structure for a Google Workspace Add-on.
// In Code.gs
function buildAddOn(e) {
return CardService.newCardBuilder()
.setHeader(CardService.newCardHeader().setTitle('My Add-on'))
.build();
}
// In manifest file, set the appropriate add-on properties
22
.setMimeType(ContentService.MimeType.JSON);
}
}
23
Sending Push Notifications
Send notifications to a device using Firebase Cloud Messaging.
function sendPushNotification() {
var url = 'https://fcm.googleapis.com/fcm/send';
var payload = {
'to': 'DEVICE_TOKEN',
'notification': {
'title': 'Test Notification',
'body': 'This is a test message.'
}
};
var options = {
'method': 'post',
'contentType': 'application/json',
'payload': JSON.stringify(payload),
'headers': {
'Authorization': 'key=SERVER_KEY'
}
};
UrlFetchApp.fetch(url, options);
}
24
Implementing Pagination
Retrieve data in chunks or pages.
function getPagedData() {
var pageSize = 50;
var pageToken = null;
do {
var response = SomeApi.getData({ pageSize: pageSize, pageToken: pageToken });
processData(response.items);
pageToken = response.nextPageToken;
} while (pageToken);
}
25
Copying a Spreadsheet
Make a copy of a spreadsheet file.
function copySpreadsheet() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var copy = ss.copy('Copy of ' + ss.getName());
}
Setting Up Webhooks
Receive POST requests to trigger script functions.
function doPost(e) {
var data = JSON.parse(e.postData.contents);
// Process data
return ContentService.createTextOutput('Success');
}
26
}
Encrypting Data
Encrypt and decrypt data using Utilities.
function encryptData() {
var text = 'Sensitive Information';
var key = Utilities.base64Encode('your-secret-key');
var encrypted = Utilities.base64Encode(Utilities.computeHmacSha256Signature(text,
key));
Logger.log(encrypted);
}
27
userEnteredValue: { stringValue: 'Hello' }
}]
}],
fields: 'userEnteredValue'
}
}];
Sheets.Spreadsheets.batchUpdate({ requests: requests }, spreadsheetId);
}
28
Error Logging to a Spreadsheet
Log errors to a dedicated sheet for monitoring.
function logError(error) {
var ss = SpreadsheetApp.openById('ERROR_LOG_SPREADSHEET_ID');
var sheet = ss.getSheetByName('Errors');
sheet.appendRow([new Date(), error.message, error.stack]);
}
function safeFunction() {
try {
// Code that might throw an error
} catch (e) {
logError(e);
}
}
29
var data = { message: 'CORS enabled' };
return ContentService.createTextOutput(JSON.stringify(data))
.setMimeType(ContentService.MimeType.JSON)
.setHeader('Access-Control-Allow-Origin', '*');
}
30
while (results.next()) {
Logger.log(results.getString(1));
}
results.close();
stmt.close();
conn.close();
}
31
var response = UrlFetchApp.fetch(url, {
headers: { 'Authorization': 'Bearer ' + ScriptApp.getOAuthToken() }
});
var data = JSON.parse(response.getContentText());
Logger.log(data.albums);
}
32
function showSidebar() {
var html = HtmlService.createHtmlOutput('<p>Custom Sidebar Content</p>');
SpreadsheetApp.getUi().showSidebar(html);
}
33
Using Regular Expressions
Extract numbers from a string using regex.
function extractNumbers() {
var str = 'Order number is 12345';
var match = str.match(/\d+/);
Logger.log(match[0]); // Outputs '12345'
}
34
function addCellNote() {
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange('A1').setNote('This is a note.');
}
35
.setRanges([range])
.build();
var rules = sheet.getConditionalFormatRules();
rules.push(rule);
sheet.setConditionalFormatRules(rules);
}
36
sheet.appendRow(['Data1', 'Data2', 'Data3']);
}
37
Creating and Deleting Drive Files
Create a text file and delete it afterward.
function createAndDeleteFile() {
var file = DriveApp.createFile('Sample.txt', 'Hello, world!');
Logger.log('File created: ' + file.getName());
file.setTrashed(true); // Moves file to trash
}
38
Using Spreadsheet Formulas via Apps Script
Set a formula in a cell using Apps Script.
function setFormula() {
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange('A1').setFormula('=SUM(B1:B10)');
}
39
method: 'get',
headers: { 'Authorization': 'Bearer your_token' }
};
var response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response.getContentText());
Logger.log(data);
}
40
.atHour(9)
.create();
}
41
function insertImage() {
var sheet = SpreadsheetApp.getActiveSheet();
var url = 'https://www.example.com/image.jpg';
sheet.getRange('A1').setFormula('=IMAGE("' + url + '")');
}
42
Body: 'Hello from Apps Script!'
};
var options = {
method: 'post',
payload: payload,
headers: {
Authorization: 'Basic ' + Utilities.base64Encode(accountSid + ':' + authToken)
}
};
UrlFetchApp.fetch(url, options);
}
Uninstalling Triggers
Delete all triggers associated with a script.
function deleteAllTriggers() {
var triggers = ScriptApp.getProjectTriggers();
triggers.forEach(function(trigger) {
ScriptApp.deleteTrigger(trigger);
});
}
43
row.forEach(function(cell, colIndex) {
if (cell === '') {
Logger.log('Empty cell at row ' + (rowIndex + 1) + ', column ' + (colIndex + 1));
}
});
});
}
44
body.replaceText('{{name}}', 'John Doe');
doc.saveAndClose();
}
45
function addDaysToDate() {
var date = new Date();
date.setDate(date.getDate() + 5); // Adds 5 days
var formattedDate = Utilities.formatDate(date, 'GMT', 'yyyy-MM-dd');
Logger.log(formattedDate);
}
46
var ui = SpreadsheetApp.getUi();
var response = ui.prompt('Enter password to unprotect the sheet');
if (response.getResponseText() === 'your_password') {
protection.remove();
}
}
Using SpreadsheetApp.openByUrl()
Open a spreadsheet by its URL.
function openSpreadsheetByUrl() {
var url = 'https://docs.google.com/spreadsheets/d/YOUR_SHEET_ID/edit';
var ss = SpreadsheetApp.openByUrl(url);
Logger.log('Opened spreadsheet: ' + ss.getName());
}
47