Blog

Google Apps Script: A Beginner’s Guide


28 Days to Gemini Mastery

New course

Stop dabbling with Gemini. Start building AI systems.

One-off prompts → repeatable workflows Gemini across all your Workspace tools
Automations and agents that save hours NotebookLM, vibe coding, Gemini Gems

What is Google Apps Script?

Google Apps Script is a cloud-based scripting language for extending the functionality of Google Apps and building lightweight cloud-based applications.

It means you write small programs with Apps Script to extend the standard features of Google Workspace Apps. It’s great for filling in the gaps in your workflows.

With Apps Script, you can do cool stuff like automating repeatable tasks, creating documents, emailing people automatically and connecting your Google Sheets to other services you use.

Writing your first Google Script

In this Google Sheets script tutorial, we’re going to write a script that is bound to our Google Sheet. This is called a container-bound script.

(If you’re looking for more advanced examples and tutorials, check out the full list of Apps Script articles on my homepage.)

Hello World in Google Apps Script

Let’s write our first, extremely basic program, the classic “Hello world” program beloved of computer teaching departments the world over.

Begin by creating a new Google Sheet.

Then click the menu: Extensions > Apps Script

This will open a new tab in your browser, which is the Google Apps Script editor window:

Google Apps Script Editor

By default, it’ll open with a single Google Script file (code.gs) and a default code block, myFunction():

function myFunction() {
  
}

In the code window, between the curly braces after the function myFunction() syntax, write the following line of code so you have this in your code window:

function myFunction() {
  Browser.msgBox("Hello World!");
}

Your code window should now look like this:

Hello World Apps Script

Google Apps Script Authorization

Google Scripts have robust security protections to reduce risk from unverified apps, so we go through the authorization workflow when we first authorize our own apps.

When you hit the run button for the first time, you will be prompted to authorize the app to run:

Google Apps Script Authorization

Clicking Review Permissions pops up another window in turn, showing what permissions your app needs to run. In this instance the app wants to view and manage your spreadsheets in Google Drive, so click Allow (otherwise your script won’t be able to interact with your spreadsheet or do anything):

Google Apps Script Access

❗️When your first run your apps script, you may see the “app isn’t verified” screen and warnings about whether you want to continue.

In our case, since we are the creator of the app, we know it’s safe so we do want to continue. Furthermore, the apps script projects in this post are not intended to be published publicly for other users, so we don’t need to submit it to Google for review (although if you want to do that, here’s more information).

Click the “Advanced” button in the bottom left of the review permissions pop-up, and then click the “Go to Starter Script Code (unsafe)” at the bottom of the next screen to continue. Then type in the words “Continue” on the next screen, click Next, and finally review the permissions and click “ALLOW”, as shown in this image (showing a different script in the old editor):

More information can be found in this detailed blog post from Google Developer Expert Martin Hawksey.

Running a function in Apps Script

Once you’ve authorized the Google App script, the function will run (or execute).

If anything goes wrong with your code, this is the stage when you’d see a warning message (instead of the yellow message, you’ll get a red box with an error message in it).

Return to your Google Sheet and you should see the output of your program, a message box popup with the classic “Hello world!” message:

Message Box Google Sheets

Click on Ok to dismiss.

Great job! You’ve now written your first apps script program.

Rename functions in Google Apps Script

We should rename our function to something more meaningful.

At present, it’s called myFunction which is the default, generic name generated by Google. Every time I want to call this function (i.e. run it to do something) I would write myFunction(). This isn’t very descriptive, so let’s rename it to helloWorld(), which gives us some context.

So change your code in line 1 from this:

function myFunction() {
  Browser.msgBox("Hello World!");
}

to this:

function helloWorld() {
  Browser.msgBox("Hello World!");
}

Note, it’s convention in Apps Script to use the CamelCase naming convention, starting with a lowercase letter. Hence, we name our function helloWorld, with a lowercase h at the start of hello and an uppercase W at the start of World.

Adding a custom menu in Google Apps Script

In its current form, our program is pretty useless for many reasons, not least because we can only run it from the script editor window and not from our spreadsheet.

Let’s fix that by adding a custom menu to the menu bar of our spreadsheet so a user can run the script within the spreadsheet without needing to open up the editor window.

This is actually surprisingly easy to do, requiring only a few lines of code. Add the following 6 lines of code into the editor window, above the helloWorld() function we created above, as shown here:

function onOpen() {
  const ui = SpreadsheetApp.getUi();
  ui.createMenu('My Custom Menu')
      .addItem('Say Hello', 'helloWorld')
      .addToUi();
}

function helloWorld() {
  Browser.msgBox("Hello World!");
}

If you look back at your spreadsheet tab in the browser now, nothing will have changed. You won’t have the custom menu there yet. We need to re-open our spreadsheet (refresh it) or run our onOpen() script first, for the menu to show up.

To run onOpen() from the editor window, first select then run the onOpen function as shown in this image:

Google Apps Script Function Menu

Now, when you return to your spreadsheet you’ll see a new menu on the right side of the Help option, called My Custom Menu. Click on it and it’ll open up to show a choice to run your Hello World program:

Custom menu

Run functions from buttons in Google Sheets

An alternative way to run Google Scripts from your Sheets is to bind the function to a button in your Sheet.

For example, here’s an invoice template Sheet with a RESET button to clear out the contents:

Button with apps script in google sheets

For more information on how to do this, have a look at this post: Add A Google Sheets Button To Run Scripts

Google Apps Script Examples

Macros in Google Sheets

Another great way to get started with Google Scripts is by using Macros. Macros are small programs in your Google Sheets that you record so that you can re-use them (for example applying standard formatting to a table). They use Apps Script under the hood so it’s a great way to get started.

Read more: The Complete Guide to Simple Automation using Google Sheets Macros

Custom function using Google Apps Script

Let’s create a custom function with Apps Script, and also demonstrate the use of the Maps Service. We’ll be creating a small custom function that calculates the driving distance between two points, based on Google Maps Service driving estimates.

The goal is to be able to have two place-names in our spreadsheet, and type the new function in a new cell to get the distance, as follows:

GAS custom function for maps

The solution should be:

GAS custom map function output

Copy the following code into the Apps Script editor window and save. First time, you’ll need to run the script once from the editor window and click “Allow” to ensure the script can interact with your spreadsheet.

function distanceBetweenPoints(start_point, end_point) {
  // get the directions
  const directions = Maps.newDirectionFinder()
     .setOrigin(start_point)
     .setDestination(end_point)
     .setMode(Maps.DirectionFinder.Mode.DRIVING)
     .getDirections();
  
  // get the first route and return the distance
  const route = directions.routes[0];
  const distance = route.legs[0].distance.text;
  return distance;
}

Saving data with Google Apps Script

Let’s take a look at another simple use case for this Google Sheets Apps Script tutorial.

Suppose I want to save copy of some data at periodic intervals, like so:

save data in google sheet

In this script, I’ve created a custom menu to run my main function. The main function, saveData(), copies the top row of my spreadsheet (the live data) and pastes it to the next blank line below my current data range with the new timestamp, thereby “saving” a snapshot in time.

The code for this example is:

// custom menu function
function onOpen() {
  const ui = SpreadsheetApp.getUi();
  ui.createMenu('Custom Menu')
      .addItem('Save Data','saveData')
      .addToUi();
}

// function to save data
function saveData() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheets()[0];
  const url = sheet.getRange('Sheet1!A1').getValue();
  const follower_count = sheet.getRange('Sheet1!B1').getValue();
  const date = sheet.getRange('Sheet1!C1').getValue();
  sheet.appendRow([url,follower_count,date]);
}

See this post: How To Save Data In Google Sheets With Timestamps Using Apps Script, for a step-by-step guide to create and run this script.

Google Apps Script example in Google Docs

Google Apps Script is by no means confined to Sheets only and can be accessed from other Google Workspace tools.

Here’s a quick example in Google Docs, showing a script that inserts a specific symbol wherever your cursor is:

Google Docs Apps Script

We do this using Google App Scripts as follows:

1. Create a new Google Doc

2. Open script editor from the menu: Extensions > Apps Script

3. In the newly opened Script tab, remove all of the boilerplate code (the “myFunction” code block)

4. Copy in the following code:

// code to add the custom menu
function onOpen() {
  const ui = DocumentApp.getUi();
  ui.createMenu('My Custom Menu')
      .addItem('Insert Symbol', 'insertSymbol')
      .addToUi();
}

// code to insert the symbol
function insertSymbol() {  
  // add symbol at the cursor position
  const cursor = DocumentApp.getActiveDocument().getCursor();
  cursor.insertText('§§');
  
}

5. You can change the special character in this line

cursor.insertText('§§');

to whatever you want it to be, e.g.

cursor.insertText('( ͡° ͜ʖ ͡°)');

6. Click Save and give your script project a name (doesn’t affect the running so call it what you want e.g. Insert Symbol)

7. Run the script for the first time by clicking on the menu: Run > onOpen

8. Google will recognize the script is not yet authorized and ask you if you want to continue. Click Continue

9. Since this the first run of the script, Google Docs asks you to authorize the script (I called my script “test” which you can see below):

Docs Apps Script Auth

10. Click Allow

11. Return to your Google Doc now.

12. You’ll have a new menu option, so click on it:

My Custom Menu > Insert Symbol

13. Click on Insert Symbol and you should see the symbol inserted wherever your cursor is.

Google Apps Script Tip: Use the Logger class

Use the Logger class to output text messages to the log files, to help debug code.

The log files are shown automatically after the program has finished running, or by going to the Executions menu in the left sidebar menu options (the fourth symbol, under the clock symbol).

The syntax in its most basic form is Logger.log(something in here). This records the value(s) of variable(s) at different steps of your program.

For example, add this script to a code file your editor window:

function logTimeRightNow() {
  const timestamp = new Date();
  Logger.log(timestamp);
}

Run the script in the editor window and you should see:

Google Apps Script Execution Logs

Real world examples from my own work

I’ve only scratched the surface of what’s possible using G.A.S. to extend the Google Apps experience.

Here are a couple of interesting projects I’ve worked on:

1) A Sheets/web-app consisting of a custom web form that feeds data into a Google Sheet (including uploading images to Drive and showing thumbnails in the spreadsheet), then creates a PDF copy of the data in the spreadsheet and automatically emails it to the users. And with all the data in a master Google Sheet, it’s possible to perform data analysis, build dashboards showing data in real-time and share/collaborate with other users.

2) A dashboard that connects to a Google Analytics account, pulls in social media data, checks the website status and emails a summary screenshot as a PDF at the end of each day.

Marketing dashboard using Google Apps Script

3) A marking template that can send scores/feedback to students via email and Slack, with a single click from within Google Sheets. Read more in this article: Save time with this custom Google Sheets, Slack & Email integration

My own journey into Google Apps Script

My friend Julian, from Measure School, interviewed me in May 2017 about my journey into Apps Script and my thoughts on getting started:

Google Apps Script Resources

For further reading, I’ve created this list of resources for information and inspiration:

Course

Documentation

Official Google Documentation

Google Workspace Developers Blog

Communities

Google Apps Script Group

Stack Overflow GAS questions

Elsewhere On The Internet

A huge big up-to-date list of Apps Script resources hosted on GitHub.

For general Javascript questions, I recommend this JavaScript tutorial page from W3 Schools when you’re starting out.

When you’re more comfortable with Javascript basics, then I recommend the comprehensive JavaScript documentation from Mozilla.

Imagination and patience to learn are the only limits to what you can do and where you can go with GAS. I hope you feel inspired to try extending your Sheets and Docs and automate those boring, repetitive tasks!

Related Articles

IFS Function in Google Sheets

The IFS function in Google Sheets is used to test multiple conditions and outputs a value specified by the first test that evaluates to true.

It’s akin to a nested IF formula, although it’s not exactly the same. However, if you find yourself creating a nested IF formula then it’s probably easier to use this IFS function.

Continue reading IFS Function in Google Sheets

SPLIT Function in Google Sheets

The SPLIT function in Google Sheets is used to divide a text string (or value) around a given delimiter, and output the separate pieces into their own cells.

SPLIT Function Examples

Let’s see a simple example using SPLIT to separate a list of names in cell A1:

Split Function Name Example

This simple SPLIT formula will separate these names, using the comma as the separator:

=SPLIT(A1,",")

The result is 5 cells, each containing a name. Note that one cell looks blank because the text string in cell A1 has two adjacent commas with a space between them. The “space” is interpreted in the same way as the names and contained in the output:

Split Function Name Example

Now watch what happens if we include a space in the delimiter, i.e. ", "

=SPLIT(A1,", ")

The function splits on the comma "," and on the space " ", so the name “Mary Jo” split in two:

Undesirable behavior with SPLIT formula

This is probably not the desired behavior.

The third argument is an optional TRUE or FALSE that determines whether SPLIT considers each individual character of the delimiter (TRUE) or only the full combination as the separator to use (FALSE).

In our example, adding FALSE ensures that it only considers the combined comma/space string as the delimiter:

=SPLIT(A1,", ", FALSE)

And the output looks like this:

Split names in Google Sheets

There is a fourth argument too, which is optional and takes a TRUE/FALS value. It determines whether to remove blank cells or not in the output.

To illustrate this, consider this arrangement of data separated by semi-colons. Note the presence of two adjacent semi-colons with no data between them:

Split Formula Fourth Argument

The fourth argument determines whether to show or hide the blank cell caused by the two adjacent semi-colons.

To keep the blank cells, add FALSE as the fourth argument:

=SPLIT(A2,",", TRUE, FALSE)

SPLIT Function in Google Sheets: Syntax

=SPLIT(text, delimiter, [split_by_each], [remove_empty_text])

It takes 4 arguments:

text

This is the text string or value in the cell that you want to split. It can also be a reference to a cell with a value in, or even the output of a nested formula, provided that output is a string or value and not an array.

delimiter

The character or characters used to split the text. Note that by default, all characters are used in the division. So a delimiter of “the” will split a text string on “the”, “he”,”t”,”h”,”e” etc.

This behavior can be controlled by the next argument:

split_by_each

This argument is optional and takes a TRUE or FALSE value only. If omitted, it’s assumed to be TRUE.

The TRUE behavior splits by individual characters in the delimiter and any combination of them. The FALSE behavior does not consider the characters separately, and only divides on the entire delimiter.

remove_empty_text

The fourth and final argument is optional and takes a TRUE or FALSE value only. If omitted, it’s assumed to be TRUE.

It specifies what to do with empty results in the SPLIT output. For example, suppose you’re splitting a text string with a "," and your string looks like this: “Ben,Bob,,Jenny,Anna”

Between the names Bob and Jenny are two commas with no value between them.

Setting this final argument of the SPLIT function to FALSE results in a blank cell in the output. If this fourth argument is omitted or set to TRUE, then the blank cell is removed and “Bob” and “Jenny” appear in adjacent cells.

SPLIT Function Notes

  • Delimiters in SPLIT are case sensitive. So “t” only splits on lower-case t’s in the text
  • The SPLIT function requires enough “space” for its output. If it splits a text string into 4 elements then it requires 4 cells (including the one the formula is in) on that row to expand into. If there is already data in any of these cells, it does NOT overwrite it but instead shows a #REF! error message
  • You can input a range as the first argument to the SPLIT function, but it requires an Array Formula wrapper to work
  • The output from the SPLIT function is an array of values that can be passed as the input into another formula, which may require the use of the Array Formula

Alternative Split Method

There’s an alternative way to split values in a Google Sheet.

Under the Data menu, there’s a feature called “Split text to columns” which will separate single columns into multiple columns, based on the delimiter you specify.

It’s a quick and easy way to split text.

Note that it overwrites existing data in your Sheet if the split columns overlap with any existing data.

Split function alternative

SPLIT Function Template

Click here to open a view-only copy >>

Feel free to make a copy: File > Make a copy…

If you can’t access the template, it might be because of your organization’s Google Workspace settings. If you click the link and open it in an Incognito window you’ll be able to see it.

You can also read about it in the Google documentation.


Advanced Examples of the SPLIT Formula in Google Sheets

Extract The N-th Word In A Sentence

You can wrap the SPLIT function output with an INDEX function to extract the word at a given position in a sentence. E.g. to extract the 4th word, use this formula:

=INDEX(SPLIT(A1," "),4)

Extract Nth Word in Google Sheets

If you combine this with a drop down menu using data validation, you can create a word extractor:

extract Nth Word Data Validation

Alphabetize Comma-Separated Strings With The SPLIT Function in Google Sheets

Suppose you have a list of words in a single cell that you want to sort alphabetically:

Formula Challenge 3

This formula will rearrange that list alphabetically:

=JOIN(",",SORT(TRANSPOSE(SPLIT(A1,","))))

It splits the string of words, applies the TRANSPOSE function to convert into a column so it can be sorted using the SORT function, and then recombines it with the JOIN function.

Formula Challenge 3 Solution

Read more in Formula Challenge #3: Alphabetize Comma-Separated Strings.

Splitting and Concatenating Strings

The SPLIT is useful in more advanced formulas as a way to divide an array into separate elements, do some work on those elements (e.g. sort them) before recombining them with another function, like the JOIN function.

For example, this array formula will add surnames to a list of first names in a cell:

=ArrayFormula(TRIM(JOIN(", ",SPLIT(A2,", ")&" Smith")))

which looks like this in your Google Sheet:

Split Function In Google Sheets To Add Surnames

Using the onion framework to analyze this formula, starting from the innermost function and working out, it splits the text string, joins on the surname “Smith”, trims the excess trailing space with the TRIM function, and finally outputs an array by using the Array Formula.

Find Unique Items In A Grouped List

Suppose you want to find unique values from data that looks like this:

Split Function To Find Uniques

You want to extract a unique list of items from the column containing grouped words, which are separated by commas.

Use this formula to extract the unique values:

=ArrayFormula( QUERY( UNIQUE( TRIM( FLATTEN( SPLIT(A2:A100,",")))),"where Col1 is not null order by Col1"))

Read more about this technique in this post: Get A Unique List Of Items From A Column With Grouped Words

Unpivot Technique

The SPLIT function in Google Sheets is used in a number of the complex IMPORT formulas for retrieving social media statistics into your Google Sheet.

The SPLIT function was combined with the FLATTEN function in this exceedingly wacky unpivot formula in Google Sheets:

=ArrayFormula(SPLIT(FLATTEN(B1:E1&"🦊"&A2:A4&"🦊"&B2:E4),"🦊"))

All in all, SPLIT is a useful function!

5 Insights From Taking A Live Cohort-Based Course (And How I’m Applying Them To My Own)

Cohort-based course transformation
Sketching Billy Broas’ Bridge of Transformation model for my cohort-based course!

In 2021, I joined 40 other entrepreneurs for the first cohort of Billy Broas’ live online cohort-based course, the Keystone Accelerator.

It’s an 8-week program covering how to market and launch cohort-based courses (CBCs).

Cohort-based courses are online courses where a group of students join at the same time and progress through the course together. Typically, students in a CBC meet online via Zoom for interactive sessions and work on course materials between sessions.

They’re fundamentally different to self-paced video courses because the emphasis shifts from being content-centric to being community-centric.

Students get the benefit of accountability, a peer group and expert teacher(s) for questions, and a community in which to celebrate wins and share challenges. CBC’s provide structure and guidance for students. Consequently, they have much higher completion rates than self-paced courses and better outcomes for students.

I joined this Keystone cohort course because I’m creating my own live training course and I wanted to learn from the experts on how to build, market and sell these types of courses.

We met twice a week for 90 minutes over Zoom – with participants calling in from all over the world – to learn an education-based marketing framework. In addition, I joined weekly peer coaching groups to brainstorm ideas and critique each other’s work in a safe environment.

Here are my top five takeaways from taking a cohort-based course that I want apply to my own course, the Pro Sheets Accelerator:

1. It Is Possible To Have Transformative Experiences Online

I’d never done a live cohort-based course before Keystone. I’d experienced plenty of webinars, in-person courses and self-paced video courses.

But this was different.

Keystone was unlike any other learning experience I’ve had.

It combined the content of an on-demand video course with the accountability, rapid feedback and community of an in-person event.

Accountability pushes you to show up and do the work.

Rapid feedback means you don’t get stuck for long periods and learn quickly from your mistakes.

Community provides a safe space to share wins and challenges and make new friends.

Combining these three factors with world-class content is the best way to facilitate the student transformation.

For first cohort of the Pro Sheets Accelerator, I want to foster a really strong community to maximize these benefits.

If you join, you’ll be in a group of 30 – 40 students, with a private course forum, peer groups and office hours, in addition to the main teaching sessions.

2. The Connections You Make Are As Valuable As The Course Content

I joined a group of 40 super smart, motivated entrepreneurs, all building their own live training courses in wildly different industries.

Some were earlier in their journeys than me, some were further along.

Together, the breadth of experiences, ideas and insights far surpassed what I, as an individual, could have achieved.

Truly a case of the whole being greater than the sum of its parts. 

I learned a lot from the peer coaching sessions, both from giving and receiving feedback. Seeing how other people solve problems, how they think and how they approach opportunities and challenges, was hugely valuable.

Like a wifi network that gets stronger as more nodes are added and interlinked, the new connections you make through a CBC improve your chances of success with your own business.

3. Learning With Others Is More Fun Than Learning Alone

I’m a firm believer that education should be enjoyable and that you learn best when you’re having fun. We should take inspiration from young children who learn through play.

If it’s enjoyable, you’re more likely to succeed.

Instead of watching the clock and counting down until the end of a boring lecture, you’re emotionally present and absorbing information. You’re in the zone of proximal development.

In the past year, we’ve all been starved of human connection and friendship.

Although CBCs are online, you’re still going through an intense shared experience with other folks.

Naturally friendships form as people get to know each other and become more comfortable. You begin to see beneath the surface and really learn from each other.

Pro Sheets Accelerator will be a fun experience. My goal is for everyone to enjoy the course first and foremost.

4. The Tangential Ideas Are Just As Valuable As The Core Content

The Keystone course I participated in is a marketing course. Its promise is that it’ll teach you how to market and sell cohort-based courses.

But along the way, I picked up tons of other ideas. Ideas that weren’t on the syllabus but arose through digressions, chats with peers or from surprise bonus sessions with guest experts.

Simply from being part of this cohort-based course, I learned about how to run one. I saw first hand how many moving pieces there are and why you need help to run one. Everything from the first onboarding call through to how to structure the live Zoom calls and exercises.

Tiago Forte, one of the world’s leading experts on CBCs who runs the hugely successful Building A Second Brain course, joined this Keystone course and added his perspective to the program.

In addition, we had workshops on the operations side of running CBCs from course director Will Mannon, and on how to create engaging experiences for our students from learning designer Andrew Barry. Both of these added valuable insights outside of the marketing curriculum of the main course.

Encouraging curiosity, fostering peer-led learning and surprising students with guest speakers are all great ways to add value to a CBC.

I plan to implement all of these in the Pro Sheets Accelerator course.

5. Less Is More in Cohort-Based Courses

When it comes to content, less is more.

What this means in practice is that the emphasis of the course shifts from cramming in as much content as possible (a traditional signal of value) to focusing on students’ transformational learning experiences.

The goal of a CBC is for your students’ life to change. You’re guiding them across the bridge from their current status quo to the new, better life.

For example, in the Keystone course, I came away with a much deeper understanding of CBCs and education based marketing. I now have a playbook I can apply to my own business.

What I don’t have is a library of 300 videos on marketing, which I would never have the time to watch, much less implement.

This realization with regards to content – that less is more – was a key shift I noticed in myself during this Keystone course.

For the Pro Sheets Accelerator cohort-based course, my original plan was to focus on making it as comprehensive as possible, covering Google Sheets and Apps Script from top to bottom.

It would have been impossible to achieve and unmanageable for students.

Now, my plan is to focus on two areas:

  1. Developing a framework and skillset for doing data analysis with Google Sheets, and
  2. Automating that framework

Yes, they’re still big topics, but they’re focussed. I can build a syllabus that goes deep into these subjects and delivers huge value, in a way that won’t overwhelm students.

The material will be relevant. Students will learn just enough to experience a transformation but not too much that it gets diluted.

Applying These Lessons To Pro Sheets Accelerator

It’s been 4 years since I launched my first online course, How To Build Dashboards in Google Sheets.

Since then, over 40,000 students from 1,000s of organizations have registered for one or more of my online courses.

All of these courses are self-serve video courses.

Now it’s time to add a new experience-based course into the mix, as the next evolution of my education business.

I’m building a cohort-based course called Pro Sheets Accelerator, which will teach you how to leverage the power of data and automation in Google Sheets to grow your business and career.

The first cohort begins at the end of April. I’m super excited to bring together a group of Sheets aficionados for a transformative learning experience. Join us!