Google Apps Script lets you do new and cool things with Google Sheets. You can
use Apps Script to add custom menus,
dialogs, and sidebars to Google Sheets. It also
lets you write custom functions for
Sheets, as well as integrate Sheets with other
Google services like Calendar, Drive, and
Gmail.
Most scripts designed for Google Sheets manipulate arrays to
interact with the cells, rows, and columns in a spreadsheet. If you’re not
familiar with arrays in JavaScript, Codecademy offers a
great training module for arrays.
(Note that this course wasn’t developed by and isn’t associated with Google.)
For a quick introduction to using Apps Script with Google Sheets, see the
5-minute quickstart guide for
Macros, Menus, and Custom Functions.
Get started
Apps Script includes special APIs to let you programmatically create, read, and
edit Google Sheets. Apps Script can interact with Google Sheets in two broad
ways: any script can create or modify a spreadsheet if the script’s user has
appropriate permissions for the spreadsheet, and a script can also be
bound to a spreadsheet, which
gives the script special abilities to alter the user interface or respond when
the spreadsheet is opened. To create a bound script, select
Extensions > Apps Script from within
Google Sheets.
The Spreadsheet service treats Google
Sheets as a grid, operating with two-dimensional arrays. To retrieve the data
from the spreadsheet, you must get access to the spreadsheet where the data is
stored, get the range in the spreadsheet that holds the data, and then get the
values of the cells. Apps Script facilitates access to the data by reading
structured data in the spreadsheet and creating JavaScript objects for them.
Reading data
Suppose you have a list of product names and product numbers that you store in
a spreadsheet, as shown in the image below.
The example below shows how to retrieve and log the product names and product
numbers.
function logProductInfo() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
for (var i = 0; i < data.length; i++) {
Logger.log('Product name: ' + data[i][0]);
Logger.log('Product number: ' + data[i][1]);
}
}
View logs
To view the data that has been logged, at the top of the script editor, click
Execution log.
Writing data
To store data, such as a new product name and number to the
spreadsheet, add the following code to the end of the script.
function addProduct() {
var sheet = SpreadsheetApp.getActiveSheet();
sheet.appendRow(['Cotton Sweatshirt XL', 'css004']);
}
The above code appends a new row at the bottom of the spreadsheet, with the
values specified. If you run this function, you’ll see a new row added to the
spreadsheet.
Custom menus and user interfaces
You can customize Google Sheets by adding custom menus, dialog boxes, and
sidebars. To learn the basics of creating menus, see the
guide to menus. To learn about customizing the
content of a dialog box, see the
guide to HTML service.
You can also attach a script function to an image or drawing within a
spreadsheet; the function will execute when a user clicks on the image or
drawing. To learn more, see Images and Drawings in Google Sheets.
If you’re planning to publish your custom interface as part of an
add-on, follow the
style guide for consistency with the
style and layout of the Google Sheets editor.
Connecting to Google Forms
Apps Script allows you to connect Google Forms with Google Sheets through
Forms and
Spreadsheet services. This feature
can automatically create a Google Form based on data in a spreadsheet.
Apps Script also enables you to use triggers, such as
onFormSubmit
to perform a specific action after a user responds to the form.
To learn more about connecting Google Sheets to Google Forms, try the Managing
Responses for Google Forms 5-minute quickstart.
Formatting
The Range
class has methods like
setBackground(color)
to access and modify the format of a cell or range of cells. The following
example shows how you can set the font style of a range:
function formatMySpreadsheet() {
// Set the font style of the cells in the range of B2:C2 to be italic.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var cell = sheet.getRange('B2:C2');
cell.setFontStyle('italic');
}
Data validation
Apps Script lets you access existing data-validation rules in Google Sheets
or create new rules. For instance, the following sample shows how to set a
data-validation rule that allows only numbers between 1 and 100 on a cell.
function validateMySpreadsheet() {
// Set a rule for the cell B4 to be a number between 1 and 100.
var cell = SpreadsheetApp.getActive().getRange('B4');
var rule = SpreadsheetApp.newDataValidation()
.requireNumberBetween(1, 100)
.setAllowInvalid(false)
.setHelpText('Number must be between 1 and 100.')
.build();
cell.setDataValidation(rule);
}
For more details on working with data-validation rules, see
SpreadsheetApp.newDataValidation()
,
DataValidationBuilder
,
and Range.setDataValidation(rule)
Charts
Apps Script lets you embed charts in a spreadsheet that represent the data in a
specific range. The following example generates an embedded bar chart, assuming
you have chartable data in cells A1:B15
:
function newChart() {
// Generate a chart representing the data in the range of A1:B15.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var chart = sheet.newChart()
.setChartType(Charts.ChartType.BAR)
.addRange(sheet.getRange('A1:B15'))
.setPosition(5, 5, 0, 0)
.build();
sheet.insertChart(chart);
}
To learn more about embedding a chart into your spreadsheet,
see EmbeddedChart
and
specific chart builders, such as
EmbeddedPieChartBuilder
.
Custom functions in Google Sheets
A custom function is similar to a
built-in spreadsheet function like =SUM(A1:A5)
except that you define the
functions’s behavior with Apps Script. For example, you could create a custom
function, in2mm()
, that converts a value from inches to millimeters, then use
the formula in your spreadsheet by typing =in2mm(A1)
or =in2mm(10)
into a
cell.
To learn more about custom functions, try the
Menus and Custom Functions
5-minute quickstart, or take a look at the more in-depth
guide to custom functions.
Macros
Macros are another way of executing Apps Script code from the Google Sheets UI.
Unlike custom functions, you activate them with a keyboard shortcut or through
the Google Sheets menu. For more information, see
Google Sheets Macros.
Add-ons for Google Sheets
Add-ons are specially packaged Apps Script
projects that run inside Google Sheets and can be installed
from the Google Sheets add-on store. If you’ve developed a script for Google Sheets
and want to share it with the world, Apps Script lets you
publish your script as an
add-on so other users can install it from the add-on store.
Triggers
Scripts that are bound to a Google Sheets file
can use simple triggers like the functions
onOpen()
and onEdit()
to respond automatically when a user who has edit
access to the spreadsheet opens or edits the spreadsheet.
Like simple triggers,
installable triggers let Google Sheets
run a function automatically when a certain event occurs. Installable
triggers, however, offer more flexibility than simple triggers and support
the following events: open, edit, change, form submit, and time-driven (clock).
Как перейти с Excel на Таблицы
Как использовать макросы и дополнения
Далее: Как использовать Таблицы для совместной работы
Содержание
- Как автоматизировать задачи с помощью макросов
- Как преобразовать макросы Excel в Google Таблицах
- Как расширить функции Таблиц с помощью дополнений
Как автоматизировать задачи с помощью макросов
Excel:
|
Таблицы:
|
---|---|
Excel 2013 и 2010 |
Автоматизируйте повторяющиеся задачи с помощью макросов в Таблицах. Если вам необходимы специальные функции, меню или окна, создайте их с помощью Google Apps Script. Рекомендации по работе с макросами
Как записать макрос
Как создать скрипт
Подробнее…. Подробнее о Google Apps Script, специальных функциях и макросах… |
Как преобразовать макросы Excel в Google Таблицах
Excel:
|
Таблицы:
|
---|---|
Excel 2010 и 2013 |
Вы можете преобразовать макросы из таблицы Microsoft Excel в Google Таблицах с помощью Google Apps Script. Apps Script позволяет создать макросы в Таблицах аналогично тому, как это можно сделать в Excel с помощью Microsoft Visual Basic for Applications. Как создать и изменить макрос в Таблицах с помощью Apps Script
Как активировать макрос в Таблицах
Совет. Дополнительная информация о том, как библиотека Apps Script может имитировать основные функции Visual Basic for Applications (VBA), приведена в блоге для разработчиков G Suite (только на английском языке). |
Как расширить функции Таблиц с помощью дополнений
Excel:
|
Таблицы:
|
---|---|
Excel 2013 Excel 2010 |
С помощью готовых дополнений вы можете расширить функции Таблиц. Например:
Как скачать дополнения
|
Google, Google Workspace, а также другие связанные знаки и логотипы являются товарными знаками компании Google LLC. Все другие названия компаний и продуктов являются товарными знаками соответствующих компаний.
Далее: Как использовать Таблицы для совместной работы
Эта информация оказалась полезной?
Как можно улучшить эту статью?
Microsoft Excel is the lingua franca of the business world! If you’ve worked for any business of any size, you’ve probably used Excel in some form or another.
Even if your school or company has moved to using Google Workspace and its cloud based products like Google Sheets, you may still receive Excel spreadsheets from your co-workers, students and others. Also, some software programs only let you export data to the Excel file format (.xls or .xlsx). Therefore, it is useful to know how to automatically convert Excel files to Google Sheets using Apps Script.
Once you convert the Excel file to Google Sheets, you may also want to import its contents into a master spreadsheet. For example, you might be a marketing manager and your marketing analyst might send you a daily report in Excel. To analyze trends over time, you decide to copy the data from these Excel files to a master Google Sheets spreadsheet. Every day, you copy the data for that day into a separate sheet in the master spreadsheet. This lets you track trends over time. This manual process can be tedious!
What if you could save the file into Google Drive from your email itself (Gmail supports this feature) and then import it into your master spreadsheet using Apps Script? In this tutorial, I will show you how to convert an Excel spreadsheet into a Google Sheets spreadsheet and then import data from it into a master spreadsheet.
Your browser does not support HTML5 video. Here is a link to the video instead.
Prerequisites
This tutorial assumes that you’re familiar with:
-
Google Sheets
-
Basic coding concepts (If you’re new to coding, please check out a series of tutorials that I’ve written on learning to code using Google Sheets and Apps Script.).
-
Creating and running Apps Scripts.
-
Authenticating and Authorizing Apps Scripts.
-
Prompting the user for input using Apps Script.
-
Triggers in Google Sheets (especially the onOpen simple trigger)
-
Working with ranges in Google Sheets using Apps Script
-
Importing CSV files into Google Sheets using Apps Script
5 steps to convert an Excel file in Google Drive to Google Sheets using Apps Script
-
Step 1 — Create a Google Sheet to use as an interface to perform the conversion
-
Step 2 — Use Apps Script to prompt the user for the Excel file’s name
-
Step 3 — Activate the Drive advanced service in Apps Script
-
Step 4 — Use Apps Script to convert the Excel file to Google Sheets
-
Step 5 — Import contents from the converted Google Sheets spreadsheet to your master spreadsheet
Step 1 — Create a Google Sheet to use as an interface to perform the conversion
Create a Google Sheets spreadsheet that will serve as the master spreadsheet where you want data from Excel to be imported. The Excel spreadsheet will be converted to a Google Sheets spreadsheet first and then data from a sheet that you specify will be imported into another (the master) Google Sheets spreadsheet.
Step 2 — Use Apps Script to prompt the user for the Excel file’s name
Open the Apps Script editor and replace the code in it with the code below.
function onOpen() { SpreadsheetApp.getUi().createMenu("Import Excel file") .addItem("Import Excel file from Drive", "main") .addToUi(); } function main() { let fileName = promptUser("Enter the name of the Excel file to import:"); if(fileName === null) { toast("Please enter a valid filename."); return; } let sheetName = promptUser(`Enter the name of the sheet in ${fileName} to import:`); if(sheetName === null) { toast("Please enter a valid sheet."); return; } toast(`Importing ${sheetName} from ${fileName} ...`); } function toast(message) { SpreadsheetApp.getActive().toast(message); } function promptUser(message) { let ui = SpreadsheetApp.getUi(); let response = ui.prompt(message); if(response != null && response.getSelectedButton() === ui.Button.OK) { return response.getResponseText(); } else { return null; } }
Try running the code from the Apps Script toolbar. When you do, you should see a prompt in your spreadsheet asking you to enter the name of the Excel file to convert and import.
If you click the [X] to close the prompt , you will see a toast notification informing you that you must enter a valid file name.
Once you enter the name of the Excel file, you’ll be prompted to enter the name of the sheet in that file to import data from. In my Excel spreadsheet, since the student grades are in a sheet called «Data», I will enter «Data» as the value and click [Ok].
When you select [Ok] a toast notification will appear informing you that data is being imported from the Excel spreadsheet.
Step 3 — Activate the Drive advanced service in Apps Script
In order to convert files from one type to another we will need to use the advanced Drive service. A «service» is a term in programming for mechanisms to access certain capabilities programmatically. The «Drive service» lets you access certain capabilities of Google Drive from your code. Apps Script provides a basic version of the Drive service and an advanced version. The basic version is called DriveApp, is easier to use and is turned on by default. The advanced version is simply called Drive, lets you access advanced features and must be activated manually.
To activate the advanced Drive service, select the +
next to Services on the sidebar menu in the code editor and select the Drive API.
Your browser does not support HTML5 video. Here is a link to the video instead.
Step 4 — Use Apps Script to convert the Excel file to Google Sheets
Once we enable the Drive API, we will use it to convert the Excel spreadsheet to a Google Sheets spreadsheet. To do this, we will follow the following steps:
-
Get the Excel file from Google Drive using
DriveApp.getFilesByName(fileName)
-
See if the file exists. If it does, we get its contents using the
getBlob()
method. -
Then we create a copy by inserting a new file with the contents. We also specify a configuration asking to use a different file format (Google Sheets) when creating the copy.
-
Finally, we return the ID of the newly created Google Sheets file.
Here is the code that implements the above logic:
function convertExcelToGoogleSheets(fileName) { let files = DriveApp.getFilesByName(fileName); let excelFile = null; if(files.hasNext()) excelFile = files.next(); else return null; let blob = excelFile.getBlob(); let config = { title: "[Google Sheets] " + excelFile.getName(), parents: [{id: excelFile.getParents().next().getId()}], mimeType: MimeType.GOOGLE_SHEETS }; let spreadsheet = Drive.Files.insert(config, blob); return spreadsheet.id; }
Then we use the above function in the main()
function to convert the Excel spreadsheet. We display a toast notification to let the user know the ID of the converted Google Sheets spreadsheet.
let spreadsheetId = convertExcelToGoogleSheets(fileName); toast(`Google Sheets File Id: ${spreadsheetId}`);
Here is the modified main()
function.
function main() { let fileName = promptUser("Enter the name of the Excel file to import:"); if(fileName === null) { toast("Please enter a valid filename."); return; } let sheetName = promptUser(`Enter the name of the sheet in ${fileName} to import:`); if(sheetName === null) { toast("Please enter a valid sheet."); return; } toast(`Importing ${sheetName} from ${fileName} ...`); let spreadsheetId = convertExcelToGoogleSheets(fileName); toast(`Google Sheets File Id: ${spreadsheetId}`); }
We are not done yet. This converted spreadsheet has some data that we now need to import into our master spreadsheet. That is the next and final step.
Step 5 — Import contents from the converted Google Sheets spreadsheet to your master spreadsheet
In this final step, we will import data from a sheet in the converted spreadsheet that the user specified to the master spreadsheet.
We will create a function called importDataFromSpreadsheet()
that accepts two parameters as input: (1) the ID of a Google Sheets spreadsheet and (2) the name of a sheet in it that contains data we want to import.
function importDataFromSpreadsheet(spreadsheetId, sheetName) { let spreadsheet = SpreadsheetApp.openById(spreadsheetId); let currentSpreadsheet = SpreadsheetApp.getActive(); let newSheet = currentSpreadsheet.insertSheet(); let dataToImport = spreadsheet.getSheetByName(sheetName).getDataRange(); let range = newSheet.getRange(1,1,dataToImport.getNumRows(), dataToImport.getNumColumns()); range.setValues(dataToImport.getValues()); return newSheet.getName(); }
Then we need to modify the main()
function to import data from the newly created Google Sheets spreadsheet into a new sheet in your master spreadsheet.
let importedSheetName = importDataFromSpreadsheet(spreadsheetId, sheetName); toast(`Successfully imported data from ${sheetName} in ${fileName} to ${importedSheetName}`);
Here is the code for the main()
function after making these changes:
function main() { let fileName = promptUser("Enter the name of the Excel file to import:"); if(fileName === null) { toast("Please enter a valid filename."); return; } let sheetName = promptUser(`Enter the name of the sheet in ${fileName} to import:`); if(sheetName === null) { toast("Please enter a valid sheet."); return; } toast(`Importing ${sheetName} from ${fileName} ...`); let spreadsheetId = convertExcelToGoogleSheets(fileName); let importedSheetName = importDataFromSpreadsheet(spreadsheetId, sheetName); toast(`Successfully imported data from ${sheetName} in ${fileName} to ${importedSheetName}`); }
That’s it, we’re done creating an automated way to convert Excel files to Google Sheets and then import data from it into a master Google Sheets spreadsheet. Now, test your code by trying to import a sheet from an Excel file in Google Drive.
Your browser does not support HTML5 video. Here is a link to the video instead.
Full code
For your convenience I’ve provided the full code below.
function onOpen() { SpreadsheetApp.getUi().createMenu("Import Excel file") .addItem("Import Excel file from Drive", "main") .addToUi(); } function main() { let fileName = promptUser("Enter the name of the Excel file to import:"); if(fileName === null) { toast("Please enter a valid filename."); return; } let sheetName = promptUser(`Enter the name of the sheet in ${fileName} to import:`); if(sheetName === null) { toast("Please enter a valid sheet."); return; } toast(`Importing ${sheetName} from ${fileName} ...`); let spreadsheetId = convertExcelToGoogleSheets(fileName); let importedSheetName = importDataFromSpreadsheet(spreadsheetId, sheetName); toast(`Successfully imported data from ${sheetName} in ${fileName} to ${importedSheetName}`); } function toast(message) { SpreadsheetApp.getActive().toast(message); } function promptUser(message) { let ui = SpreadsheetApp.getUi(); let response = ui.prompt(message); if(response != null && response.getSelectedButton() === ui.Button.OK) { return response.getResponseText(); } else { return null; } } function convertExcelToGoogleSheets(fileName) { let files = DriveApp.getFilesByName(fileName); let excelFile = null; if(files.hasNext()) excelFile = files.next(); else return null; let blob = excelFile.getBlob(); let config = { title: "[Google Sheets] " + excelFile.getName(), parents: [{id: excelFile.getParents().next().getId()}], mimeType: MimeType.GOOGLE_SHEETS }; let spreadsheet = Drive.Files.insert(config, blob); return spreadsheet.id; } function importDataFromSpreadsheet(spreadsheetId, sheetName) { let spreadsheet = SpreadsheetApp.openById(spreadsheetId); let currentSpreadsheet = SpreadsheetApp.getActive(); let newSheet = currentSpreadsheet.insertSheet(); let dataToImport = spreadsheet.getSheetByName(sheetName).getDataRange(); let range = newSheet.getRange(1,1,dataToImport.getNumRows(), dataToImport.getNumColumns()); range.setValues(dataToImport.getValues()); return newSheet.getName(); }
Conclusion
In this tutorial I showed you how to automatically convert Microsoft Excel files into Google Sheets using Apps Script. Post conversion, the data from the newly created Google Sheets spreadsheet can also be automatically imported into a master spreadsheet. Hopefully this tutorial helps you automate manual and repetitive workflows to save you time.
Thanks for reading!
Stay up to date
Follow me via email to receive actionable tips and other exclusive content. I’ll also send you notifications when I publish new content.
By signing up you agree to the Privacy Policy & Terms.
Have feedback for me?
I’d appreciate any feedback you can give me regarding this post.
Was it useful? Are there any errors or was something confusing? Would you like me to write a post about a related topic? Any other feedback is also welcome. Thank you so much!
In this post we’re going to look at how we can get data from an Excel spreadsheet and import some of it into a Google Sheet. As an example, we’re going to upload an Excel which contains the current month’s royalty data from Amazon and add it to a central sheet which contains all the previous month’s royalties.
Similar to the post on converting a PDF document to text, this tutorial from Baz Roberts uses a similar approach of using the Google Drive API for file conversion, this time converting a MS Excel file into Google Sheets to make it possible to easily extract and update a master spreadsheet. The post includes a detailed explanation of the shared code.
Source: Importing Amazon royalty data from Excel to Google Sheet – Learning Google Workspace & Apps Script
Google Sheets has a large number of built-in functions, including many that you don’t need. However, it does not have everything. At some point, you may want to do a particular task but can’t find a function for that. Well, that doesn’t mean you can’t do it. You may only need to take a few steps to get there. 🙂
With Google Apps Script, you can do a lot. It basically allows you to create your own functions, automate a lot of stuff, and even integrate Google Sheets with other third-party services.
The Google spreadsheet Apps Script tutorial in this article covers the basics of Google Apps Script, including several easy-to-follow examples. We will focus more on Google Sheets, though you can also write code in Google Docs, Forms, or a standalone script.
What is Google Apps Script?
Google Apps Script (GAS) is a development platform that allows you to create applications that integrate with Google Workspace apps and services.
It uses modern JavaScript as its scripting language. You don’t need to install anything. Google gives you an integrated code editor that allows you to edit your scripts within your browser. Your scripts execute on Google’s servers.
GAS plays a similar role in Google Sheets as Visual Basic for Applications (VBA) does in Excel. Both are used to extend functionality and integrate with other applications and third-party services.
What makes Google Apps Script useful?
Here are a few reasons why you would need Google Apps Script:
- Create Google Sheets custom functions.
- Add custom menus, dialogs, and sidebars to Google Docs, Sheets, and Forms.
- Interact with other Google Workspace apps and services, including Docs, Gmail, Calendar, Language, Docs, and more.
- Automate tasks using triggers.
- Build add-ons for Google Sheets, Docs, Slides, and Forms, and also publish them to the Google Workspace Marketplace.
- Develop a user interface and publish it as a web app.
- Connect with external relational databases (including Google Cloud SQL, MySQL, SQL Server, and Oracle) via the JDBC service.
What are Google Apps Script classes?
Classes are templates that encapsulate data with code for creating objects. Historically, JavaScript was class-free, so talking about classes may cause confusion. The classes described here are specific to Google implementations — Google refers to SpreadsheetApp
, GmailApp
, etc., as classes.
Google Apps Script provides several top-level classes. These main classes allow you to access features of other Google apps and services, for example:
- Google Sheets can be accessed using
SpreadsheetApp
class - Google Docs can be accessed using
DocumentApp
class - Google Drive can be accessed using
DriveApp
class - Gmail can be accessed using
GmailApp
class - Language service can be accessed using
LanguageApp
class - And more
Apps Scripts also provides base classes. These allow you to access user info, such as email addresses and usernames, and also control script logs and dialog boxes. Some examples of base classes:
Browser
– provides access to dialog boxes specific to Google Sheets.Logger
– allows the developer to write out a value to the execution logs.Session
– provides access to session information, such as the user’s email address (in some circumstances) and language setting.
In this Google Apps Script Sheets tutorial, we will also use some of the classes mentioned above. For example, we’ll use the SpreadsheetApp
class to access Google Sheets’s functionalities and the LanguageApp
class to access Google’s language service.
Note: In February 2020, Google introduced the V8 runtime for Apps Script, which supports classes. This new runtime lets you create your own classes, which provide a means to organize code with inheritance. Think of it as creating a blueprint from which copies can be made.
Getting started with Google Apps Script
Enough intro — let’s dig in! 🙂
The best way to learn Google Apps Script is to write some code. Getting started is very straightforward — all you need is a Google account, a browser, and an internet connection.
To get started, go to Google Drive and create a new spreadsheet. Give your spreadsheet a name, for example, My First Script.
You can open the Apps Script editor by clicking Extensions > Apps Script from the menu (or Tools > Script editor if you can’t find the Extensions menu).
This will launch the Apps Script editor in a separate tab in your browser.
How to use Google Apps Script Editor
Now, we’ll show you how to use the Apps Script editor. For example, how to rename your project, add a new function, and save your changes.
How to rename your project
Scripts are organized as projects. By default, the project name for your scripts embedded within the spreadsheet file you just created is “Untitled project”.
At the top left, you’ll see the project name. Click on it to rename it. A small window will appear, allowing you to enter a new project title.
There is also a Code.gs file opened in the editor. It has a default function, which is blank, named myFunction()
.
function myFunction() { }
How to add your first function
Delete the myFunction()
code block so that your editor is now blank. Then, copy and paste the following code:
function writeHelloWorld() { var greeting = 'Hello world!'; var sheet = SpreadsheetApp.getActiveSheet(); sheet.getRange('A1').setValue(greeting); }
Your entire code will look like this:
The above writeHelloWorld()
function writes “Hello world!” to the spreadsheet. It demonstrates that, by using Apps Script, you can manipulate a spreadsheet.
The code uses the SpreadsheetApp
class to get an object representing the active sheet using the getActiveSheet()
method. Then, it gets a single cell with the address A1 using the getRange()
method. Another method, setValue()
, is then called with a string argument to write to A1.
How to save your changes
Notice that there is an orange circle icon on the left side of the Code.gs file name. It means your changes have not been saved yet.
To save your changes, press Ctrl+S on your keyboard. Alternatively, you can click the disk icon (). After that, the orange icon will be gone, and you’ll be able to run your script.
How to run Google Apps Script
Click the Run button to execute your function. For the first time you run the script, you will need to authorize it to access your data.
Click the Review permissions button. Another pop-up will appear, asking you to select an account to continue. After that, you may see a warning screen saying “Google hasn’t verified this app“. Continue anyway — because, in this case, we know it’s safe. Then, allow the script to access your Google account.
Once authorized, the writeHelloWorld()
function will execute, and you’ll see “Hello world!” in A1:
Google Apps Script examples
Now, let’s look at some more interesting examples using Apps Script.
Connect to other Google apps using Google Apps Script
The following example shows that a GAS written in one app (Sheets) can be used to manipulate other Google apps (Docs). Though trivial and useless, this example demonstrates a very powerful feature of GAS!
Copy and paste the following function into your editor, then click the Run button to execute it.
function createDocument() { var greeting = 'Hello world!'; var doc = DocumentApp.create('Hello_DocumentApp'); doc.setText(greeting); doc.saveAndClose(); }
Once authorized, it will create a new Google Document with “Hello world!” written on it.
You may find it’s a bit inconvenient always having to open the editor when executing your code. A simple solution for that is to add a custom menu.
You can add the code for the custom menu within the onOpen()
function. A trigger will then execute your code inside this function every time you open the spreadsheet. Here’s an example:
function onOpen(e) { var ui = SpreadsheetApp.getUi(); ui.createMenu('My Custom Menu') .addItem('First item', 'function1') .addSeparator() .addSubMenu(ui.createMenu('Sub-menu') .addItem('Second item', 'function2')) .addToUi(); } function function1() { SpreadsheetApp.getUi().alert('You clicked the first menu item!'); } function function2() { SpreadsheetApp.getUi().alert('You clicked the second menu item!'); }
Note: The e
parameter passed to the function is an event object. It contains information about the context that caused the trigger to fire, but using it is optional.
To test it, select the onOpen()
function in the dropdown, then click the Run button.
You’ll see “My Custom Menu” in your spreadsheet menu, as shown in the following screenshot:
The onOpen()
function is one of GAS’s reserved function names. Whenever you open a document, a built-in trigger executes this function first. These built-in triggers are also called simple triggers and do not need user authorization.
Other reserved function names include onEdit()
, onInstall()
, onSelectionChange(e)
, onFormSubmit()
, doGet()
, and doPost()
. Make sure you don’t use these as your function names.
Automate tasks using Google Apps Script trigger
GAS lets you create your own triggers. These triggers are also called installable triggers because you need to authorize them before use.
With installable triggers, you can set your script to run at a certain event (when opening or editing a document, etc.) or on a schedule (hourly, daily, etc.).
Notice the following script. The getBitcoinPrice()
function gets the data in the last 24 hours from the Bitstamp trading platform and outputs them in a sheet.
function getBitcoinPrice() { var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); // Get the sheet with the name Sheet1 var sheet = spreadsheet.getSheetByName("Sheet1"); var header = ['Timestamp','High','Low','Volume','Bid','Ask']; // Insert headers at the top row. sheet.getRange("A1:F1").setValues([header]); var url = 'https://www.bitstamp.net/api/ticker/'; var response = UrlFetchApp.fetch(url); // Proceed if no error occurred. if (response.getResponseCode() == 200) { var json = JSON.parse(response); var result = []; // Timestamp result.push( new Date(json.timestamp *= 1000) ); // High result.push(json.high); // Low result.push(json.low); // Volume result.push(json.volume); // Bid (highest buy order) result.push(json.bid); // Ask (lowest sell order) result.push(json.ask); // Append output to Bitcoin sheet. sheet.appendRow(result); } else { // Log the response to examine the error Logger.log(response); } }
Other than running it manually, you can create a trigger that runs the function, let’s say, every hour. And you can create a trigger either using a script or UI.
How to create a trigger using a script
To create a trigger that executes the getBitcoinPrice
function every hour, copy and paste the following function to the editor:
function createTrigger() { ScriptApp.newTrigger('getBitcoinPrice') .timeBased() .everyHours(1) .create(); }
Then, run the function manually by clicking the Run button.
Note: Do not run the createTrigger()
function more than once, or you’ll end up creating multiple triggers instead of just one.
Wait a few hours, and you should see the output in your spreadsheet, similar to the screenshot below:
You can see the list of triggers you created on the Triggers page, which can be opened from the left menu:
The Triggers page:
How to create a trigger using UI
You can also create a trigger manually from the Triggers page. But before that, let’s add this new function to send bitcoin prices as an email with a PDF attachment.
function sendEmailBitcoinPricesPdfAttachment() { var file = SpreadsheetApp.getActiveSpreadsheet().getAs(MimeType.PDF); var to = 'youremail@domain.com'; // change to yours GmailApp.sendEmail(to, 'Bitcoin prices', 'Attached prices in PDF', { attachments: [file], name: 'BitcoinPrices via AppsScript' }); }
Then, on the Triggers page, click the Add Trigger button. A new pop-up will appear, allowing you to configure a new trigger.
To set a trigger that runs the sendEmailBitcoinPricesPdfAttachment()
every day, use the following configuration:
Explanations of the options above:
- Choose which function to run: select the
sendEmailBitcoinPricesPdfAttachment()
function we just created. - Choose which deployment to run: use Head to test code.
- Select event source: select Time-driven to run the function on a schedule.
- Select type of time-based trigger: select Day timer to run the function daily. Another dropdown will appear, allowing you to select the time of day when the function will run. Note: In the above screenshot, the time is set to 8 a.m. to 9 a.m., which means it will run at some time between these hours.
- Failure notification settings: by default, you will be notified daily if the trigger fails to run. Optionally, you can change it to hourly, weekly, or even immediately.
When finished, don’t forget to click the Save button.
Custom function examples using Google Apps Script
Google Sheets offers hundreds of built-in functions like SUM, AVERAGE, CONCATENATE, and also more advanced functions like VLOOKUP, REGEXMATCH, and QUERY. When these aren’t enough for your needs, you can use GAS to write your own functions.
Let’s look at a few examples of custom functions below.
Example #1. Custom numeric function using Google Apps Script
Here’s a simple custom function named AREAOFCIRCLE
. The function calculates the area of a circle by taking a single numeric argument, which is the radius of the circle, and returns the area of a circle using the formula: PI * radius2
. It also validates that the radius is numeric and not less than 0.
/**Returns the area of the circle from the specified radius input. * * @param {number} radius * @return {number} * @customfunction */ function AREAOFCIRCLE (radius) { if (typeof radius !== 'number' || radius < 0){ throw Error('Radius must be a positive number'); } return Math.PI * Math.pow(radius, 2); }
To use the function, write a few radius values in your spreadsheet. Then, type an equals sign followed by the function name and any input value. For example, type =AREAOFCIRCLE(A2)
and press Enter. A nice thing here is that you can see the auto-complete shows the description of the new custom function:
Copy the formula down, and you’ll see the following result:
Notice that there’s an error in B5. That’s because xxxxx
is not a numeric value. Thus, using =AREAOFCIRCLE(A5)
returns an error message that we defined in the code.
Example #2. Custom string function using Google Apps Script
In the following example, you will see how custom functions can be used to access other Google services, such as the language service.
The following functions perform translations from English to other languages. Each of the functions takes a string argument and translates it to a different language: French, Spanish, or Italian.
function ENGLISHTOFRENCH(english_words) { return LanguageApp.translate(english_words, 'en', 'fr'); } function ENGLISHTOSPANISH(english_words) { return LanguageApp.translate(english_words, 'en', 'es'); } function ENGLISHTOITALIAN(english_words) { return LanguageApp.translate(english_words, 'en', 'it'); }
Example usage in a spreadsheet:
The functions seem to work well for a straightforward and non-idiomatic phrase. And you can use those functions to help you translate English words to other languages. However, it’s always best to check again with native speakers for the accuracy and quality of the translations.
Example #3. Custom date function using Google Apps Script
The following function returns an array of dates, which are the first day of each month for the given year, including their day names. This demonstrates that a custom function can also return a two-dimensional array.
function FIRSTDAYOFTHEMONTH(year) { var array = []; for (var m = 0; m <= 11; m++) { var firstDay = new Date(year, m, 1); var dayName = ''; switch(firstDay.getDay()) { case 0: dayName = 'Sunday'; break; case 1: dayName = 'Monday'; break; case 2: dayName = 'Tuesday'; break; case 3: dayName = 'Wednesday'; break; case 4: dayName = 'Thursday'; break; case 5: dayName = 'Friday'; break; case 6: dayName = 'Saturday'; break; } array.push([(m+1) + '/1/' + year, dayName]); } return array; }
Type in a cell, for example, =FIRSTDAYOFTHEMONTH(2021)
in A1. You’ll see a result like this:
Example #4. Custom web function for importing CSV using Google Apps Script
Suppose you want to import CSV data from a published online file. Google Sheets has a built-in function called IMPORTDATA for that. But when doing the import, you may want to add some filters. For example, to exclude several columns. In this case, you can use the IMPORTDATA in combination with the QUERY function to give you more options.
Another alternative — you can write your own function using GAS to avoid writing several functions in one cell. Here’s an example:
function CUSTOMCSVIMPORT(url, columns) { var csvContent = UrlFetchApp.fetch(url).getContentText(); var csvData = Utilities.parseCsv(csvContent); // Remove all white spaces, change to lower case, and split. var requiredColumns = columns.split(","); // Get the indexes of required columns var indexesOfRequiredColumns = []; if (requiredColumns.length > 0) { for (var i = 0; i < csvData[0].length; i++) { if (requiredColumns.includes((csvData[0][i]))) { indexesOfRequiredColumns.push(i); } } } if (indexesOfRequiredColumns.length > 0) { return csvData.map(r => indexesOfRequiredColumns.map(i => r[i])); } return csvData; }
The above function allows you to import a CSV file from a URL and choose only a few columns to import.
The function has two parameters: url
and columns
. The second parameter (columns
) accepts column names, each concatenated with a comma, for example: “columnname1,columnname2,...”
Example usage in a spreadsheet
In the following screenshot, you can see that only the columns specified in B2 are returned in the spreadsheet:
- B1 cell contains the URL of a CSV file
http://samples.openweathermap.org/storage/history_bulk.csv?appid=b1b15e88fa797225412429c1c50c122a1
- B2 cell contains the columns to import
dt,dt_iso,city_name,temp_min,temp_max,weather_main,weather_description
Can I use custom functions with ARRAYFORMULA?
You can’t nest custom functions with ARRAYFORMULA, but, you can modify your function to input and return a range in the form of a two-dimensional array. This will also optimize the performance of your spreadsheet, since each custom function run requires a call to the Apps Script server. The more custom functions calls are sent, the slower the performance of your spreadsheet will be.
Here is an example of a simple custom function that converts Fahrenheit to Celsius:
function FtoC(input) { return (input - 32) * 0.5556; }
We modified it to accept both a single cell and a range of cells, as follows:
function FtoC(input) { return Array.isArray(input) ? input.map(row => row.map(cell => (cell - 32) * 0.5556)) : (input - 32) * 0.5556; }
So, now you can type in =ftoc(A2:A5)
and get the desired outcome.
Google Apps Script alternative: Coupler.io
Coding your own GAS function for importing data (as shown earlier with the CUSTOMCSVIMPORT
function) may require a lot of effort. You’ll need to test various scenarios, try different filtering criteria, and so on.
If you’re looking for a convenient solution that is powerful and does not require any coding, you may want to try Coupler.io. It’s an integration tool that allows you to import data from CSV and other popular data sources into Google Sheets.
Coupler.io also offers more features than the IMPORTDATA function does. For a detailed comparison, you may want to check out this comparison table: IMPORTDATA vs. Coupler.io.
Here’s an example screenshot of selecting CSV data source in Coupler.io:
Simply copy and paste the CSV URL to import:
Optionally, you can specify which fields to import and even skip some rows if you’d like to:
And more interestingly, you can set up an automatic data refresh on a schedule:
Google Apps Script limitations
As GAS runs on Google’s server, Google sets limits on its execution, such as:
- A script cannot run continuously for more than 6 minutes. So, for example, if you use “looping” in your function, ensure that it is bug-free and will not cause an endless execution. Also, avoid handling a huge dataset that may cause the script to run for more than 6 minutes.
- A custom function cannot execute for more than 30 seconds. So, avoid handling large external data using custom functions. Otherwise, you may see a “Maximum execution time exceeded” error.
Please note that the above limitations may change in the future. You can find the complete list of GAS limitations here.
How can I learn more about Google Apps Script
In this Google Apps Script tutorial, you’ve learned how to create custom functions, custom menus, and access to other Google apps and services. However, GAS is powerful, and you can do a lot more, such as creating add-ons, publishing web apps, and connecting to external databases.
If you want to learn more about Google Apps Script, one common suggestion is to learn JavaScript and follow the numerous tutorials available on the internet. Well, there is no doubt that the number of tutorials on the internet is huge and they can be overwhelming.
Therefore, we suggest you start with the following sources:
- Documentation on Apps Script by Google.
- Samples, codelab, video tutorials, articles, and other learning resources for Apps Script by Google.
And here are some other free and useful resources:
- Eloquent JavaScript – ebook by Marijn Haverbeke; it’s free digitally.
- Apps Script Blastoff! – free introductory Apps Script course by Ben Collins.
- Stackoverflow entries for Google Apps Script – ask questions here.
- Apps Script open issues – post any issues (or enhancement requests) here.
Happy learning and enjoy! 🙂
-
Senior analyst programmer
Back to Blog
Focus on your business
goals while we take care of your data!
Try Coupler.io