Add a Row of Data Below the Header in Google Sheets with Apps Script

Sometimes it is just more intuitive to add a row of data to a Google Sheet just below the header instead of at the bottom of the Sheet.

One instance when this comes to mind is when we need to monitor time-dependent data as it is being input programmatically based on a trigger through Google Apps Script. Seeing purchases or sign-ins at the top of your sheet live might be more convenient than at the bottom of the sheet.

In this tutorial, we will walk through how to insert a row and add a new row of data to that row. We’ll also look at how to maintain formatting during this process.

Then if you need to maintain a Named Range or Some formula columns, we’ll walk through that too.

Let’s dive in!

The Starter Sheet

If you want to try out the script examples directly or are playing along from the video tutorial, here is a copy of the starter script:

Add a Row of Data Below the Header with Apps Script – STARTER

The Video

The Basic Code to Add a Row after A Header

In this example, we have a simple Google Sheet where we need to add our data to a row just below the header.

Simple example of adding a row below the header in Google Sheets With Apps Script
A simple example of adding a row below the header in Google Sheets With Apps Script

The main run function is the insertRowAtTop_v1() function. This contains all the code we need to complete our task.

The runsies_example1() function is simply a sample function that simulates how you can integrate the insertRowAtTop_v1() function into your own project.

If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.

insertRowAtTop_v1()

Set up the function

The insertRowAtTop_v1() function takes 3 arguments:

  1. data – This is a 2d array of data containing the values you want to enter into your new row.
    Google Sheet data is presented as a 2d array in Google Apps Script where a row of data is an entire array and each row array is contained in an outer array. So for example, a sheet range that is 3 columns by 4 rows deep would look like this:
  2. sheetName – This is the sheet tab name.
  3. targetRow – This is the row where you want to insert your range. If your header data is deeper than one row, then you can change this value.

First, we call the getActiveSpreadsheet() method from the Google Apps Script SpreadsheetApp class. You can use the openById() or openByUrl() methods.

Now that we have access to our sheet we can invoke the getSheet() method taking the selected sheet as our parameter. For our example, the sheet will be ‘Example 1’ as indicated by the sheetName parameter.

insert a row into the sheet

Our next task is to add a row to our sheet. We can do this with the .insertRowBefore(targetRow) method. This method takes a target row as a parameter. For us, our argument for this parameter is row 2Line 21

This method will insert a row above the target row.

Now you might have also seen the .insertRowAfter() method and may be wondering why this was not used. These insert methods reference their formatting (i.e. Font, font colour, borders, background colours etc.) from the target row. So if we used the ‘after’ method we would have the header formatting in our cell, which is not what we want.

add data to the new row

With the new row added, we can add the data to that range.

First, we need to get the range where we will add our data. We do this with the getRange() method. This can take a number of parameter formations, but we will use the 4-integer set. These include:

  1. Row Start – This will be the target row we set.
  2. Column Start – All our data will begin in Column A so we set this to one.
  3. Row Depth – We are only inserting one row of data so our depth will be one.
  4. Column Width – The width of the range will be determined by the width of the data that we will put into it. This means that if we get the length or total count of each cell item in the row then this will be the column width.
    We can do this by using the JavaScript length property. Note that we need to get the length of the inner array (data[0].length). This is done by referencing the first or zeroeth item in the array. Line 23

Now that we have our range we can set the values from our data parameter. We do this using the setValues() methodLine  24

Flush the Spreadsheet

Flush Your SpreadsheetWhile Google Apps Script will try and bundle your data together into one operation, a Flush can ensure that all operations on the spreadsheet are complete before any other operations are done on the sheet.

We achieve this with the SpreadsheetApp.flush() method.

runsies_example1()

This example function helps us to understand what parameters we can enter into insertRowAtTop_v1().

Here we set our target row to row 2 and the sheet name to ‘Example 1’.

For our dummy data, we will abuse the JavaScript Date constructor to generate the current date time stamp (Line 39). Then we will convert the date to a time in milliseconds with the getTime() method (Line 40).

We will then use the time as an ID, the date as, well… the date and build a dummy email from the time and a ‘@example.com’ string.

After that, add these variables into the function insertRowAtTop_v1() call parameters.

Handling The Edge of a Named Range

In this example,  we have added a named range to our data range. Perhaps to make it easier to handle the data in another operation in our sheet or in our script.

However, if we were to run our script in ‘Example 1’ above on this we would find that after inserting a new row, our Named Range will change its range. It will go from ‘Example 2’!A2:C15 to ‘Example 2’!A3:C16  as you can see in our Example 2 sheet DataSet named range in the image below. Each subsequent addition to the range will add another row to the DataSet named range.

This will cause problems for us because it will miss the new data we add.

We need to fix this.

Adding a row below the header in Google Sheets with a Named Range With Apps Script

Check out the code for our updated function insertRowAtTop_v2():

Update insertRowAtTop_v2()

In this updated version we have added an extra parameter called namedRangeName. In our example, this will be the DataSet named range. Line 8

On lines 22-26, we need to update the named range, maintaining the existing row and column height, and column width but expanding its row depth.

Two new variables

Lines 13 and 14 add two new variables to our function and will be used to recalculate the range of our named range:

  1. rowDepth: This is the last row number subtracted by the target row + 3. In the example image above our target row is row 2. The last row with data is row 14. If we subtract 14 from 2 we get 12. However, we have 13 items in our sheet and our name range also included an empty space at the bottom – Which means we need to add 2. We will also add an extra row during our process so now our formula would look like this:
    14 - 2 + 3 = sheet.getLastRow() - targetRow + 3
  2. colWidth: We will now need to get the column width twice from our data parameter. Once when we get the range and, once when we get the width of the named range. Let’s call the length property only once (data[0].length) and then reference the resulting value.

find the named range and update it

The only way we can update a named range with the SpreadsheetApp class is to first get an array of all named ranges in the spreadsheet. This is done with the getNamedRanges() methodLine 22

From here we can use the JavaScript Find method that will return the first matching item in the array. Line 23

.find(namedRange => namedRange.getName() === namedRangeName)

The Find method takes a function as an argument containing an iterator parameter that we set to namedRange. This will run through each named range in the array until it finds our desired match.

For simplicity, we are using an arrow function here.

On each iteration, we can call the getName() method on the selected named range and compare that with our namedRangeName parameter (e.g. ‘DataSet’). If there is a match Find will conclude its iteration and return the current named range.

Once we have our selected named range we can use the setRange() method to update the range (Line 25). This method takes another range construct as an argument (Line 26).


Here we set the start row to our target row in column A and then assign our row depth and column widths we generated earlier in the function.

Including preexisting formulas into the newly inserted row

You may have a scenario where you have some formulas in your sheet that you need to add to your data row when it is added to your Google Sheet.

In our ‘Example 3’ sheet tab, we have added two formula rows to our data set in columns D and E that we want to include in our new row entries.

Adding a row below the header in Google Sheets with a Named Range and formula columns With Apps Script

Let’s take a look at the updated function now:

Here we have included a new optional parameter hasFormulas that is set to false by default. You can set this option to true if you wish to include formulas at the end of your row input. Line 9 

Adding the formulas to the input

We have included an if condition after we created our row on lines 21-27. Here we check if the sheet has formulas at the end. If it does then get the total number of columns in the sheet with the getMaxColumns method.  Line 22

Next, we need to get the ranges for the newly inserted row (rowAbove) and the row below it (rowBelow). We will add one to the row to grab the row below and apply the maxCols variable from line 22 to indicate the width of the range.

Finally, we will copy the row below in its entirety to the row above with the copyTo method.

The format for this method is as follows:

sourceRange.copyTo(destinationRange)

Without any other optional parameters, this method will copy over the formatting and the formulas from the previous range. If the formulas are not set to absolute ranges (with the $ sign) then they will adjust automatically to the new cell range.

Conclusion

While there are probably still some edge cases that these examples don’t cover, I think that they will handle the majority of scenarios that you come across. The examples should also provide you with some understanding of the workings of the code to make your own modifications where you see fit.

It’s always interesting to hear how you apply the scripts to your own projects. Feel free to comment below.

Further Reading

If you are looking for an alternative approach to adding data to a sheet check out these tutorials:

Looking to learn more about Google Apps Scripts in a more structured format? Udemy has some great courses that can get you from the basics to a real Google Apps Script pro.

Got a more specific problem you need help with, but don’t have the time to develop the skills? Make an enquiry on my 'Hire me!' page. I occasionally pick up projects. Alternatively, Fiverr’s your best bet to find a skilled Google Apps Script developer to solve your problem quickly and professionally. *

*The above affiliate links have been carefully researched to get you to what you specifically need. If you decide to click on one of these links it will cost you just the same as going to the site. If you decide to sign up, I just get a little pocket money to help pay for the costs of running this website.

If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.

Develop a Google Chat App Currency Converter with Google Apps Script

Have you ever wanted to convert currencies instantly while in Google Chat with colleagues and clients? In this tutorial, we are going to build a Currency Converter Google Chat App with Google Apps Script to do just that.

This tutorial is a multi-media series containing step-by-step video instructions for each stage of the process along with code snippets for each stage, important links and some further details on the more unusual parts of the code.

We start off our project adventure having already made a copy of the Google Apps Script Chat App project, connecting it to a Google Cloud Platform (GCP) project and deploying it for the first time. You can find out how to set up this stage by heading over to the Google Chat Apps for Google Apps Script Developers tutorial or directly to the YouTube tutorial.

It is important to note that Chat Apps and their development are only available for Google Workspace paid accounts.

What we are Building

In this tutorial, we will be creating a Currency Converter chat app that generates a currency conversion based on a slash command inside Google Chat or Space. The syntax will be:

/xe  amount from_currency_code:to_currency_code

For example:

/xe 1,230.95AUD:USD

This will return

 1,230.95 AUD =  795.2 USD

1 AUD = 0.64601 USD
1 USD = 1.54798 AUD

(Last updated: 2022-10-07)

Convert a currency inside a Google Chat Space Example

We will also provide two more slash commands:

  1. /xe-help – This will provide instructions for the user on how to enter a conversion.
    Google Chat App Currency Converter xe-help slash command example
  2. /xe-list – This will provide a list of all currency codes.
    Google Chat App Currency Converter xe-list slash command example

Looking to learn more about Google Apps Scripts in a more structured format? Udemy has some great courses that can get you from the basics to a real Google Apps Script pro.

Got a more specific problem you need help with, but don’t have the time to develop the skills? Make an enquiry on my 'Hire me!' page. I occasionally pick up projects. Alternatively, Fiverr’s your best bet to find a skilled Google Apps Script developer to solve your problem quickly and professionally. *

*The above affiliate links have been carefully researched to get you to what you specifically need. If you decide to click on one of these links it will cost you just the same as going to the site. If you decide to sign up, I just get a little pocket money to help pay for the costs of running this website.

1. Create the /xe and /xe-help slash commands

In this first part of the tutorial series, we need to create two main slash commands /xe and /xe-help. To do this we will update the onMessage() trigger function. Then we will connect the slash commands in the GCP Google Chat API configuration GUI.

We will also update the Google Apps Script Chat App template to return messages more specific to our currency converter.

Video 1

If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.

The Code

Code.gs

CurrencyGlobals.gs

SlashCommands.gs

appsscript.json

In your appsscript.json file, add the following:

For me this would look like this:

2. Connecting our Google Apps Script to the Exchange Rates Data API

At this stage of the tutorial, we will build our connector to our currency exchange API. We will create a quasi-class (CurrencyAPI()) with a method to get a list of all currencies (.getCurrencyList()) and retrieve a currency conversion (.convertCurrency()).

Accessing the API is done through the Google Apps Script UrlFetchApp Class with the .fetch() method. This will return two important methods worth noting:

  1. .getContentText() – The returned text from the fetch. For us, this will be a stringified JSON.
  2. .getResponseCode() – The response code. 200 to indicate a good response and the rest of the codes are errors. You can see the full list of error codes from the API here.

After that, we will need a way to check for any error codes that our fetch request may generate. We will create a private function for this to return either the text if the request is successful or error information.

We will be connecting to the Exchange Rates Data API. The API has a free tier of 250 requests each month. There is no requirement for a credit card or anything.

Video 2

Tutorial Links – For part 2

The Code

CurrencyAPI.gs

Create this file to store your Currency API connector.

Test.gs

Create this file to use for testing certain stages of your project.

CurrencyGlobals.gs – Add to. 

Add the currency code to the bottom of this file.

3. Connecting our Google Apps Script to the Exchange Rates Data API

Before sending our slash command info from our Google Chat App to the API to retrieve the currency conversion, we need to ensure that the user has provided valid input.

The expected input from the user is as follows:

/xe [amount]source_currrency_code:destination_currency_code

For example,

/xe 115.44AUD:USD

Note! Before we dive into our validation, it’s important for me to point out that I am basing my validation rule on the UK and US English separator convention of 1,000,000.00 or 1000000.00. Please modify the rules to meet your own country’s requirements.

What we will allow

It’s okay, particularly when working with text inputs, to be a little flexible in how a user might input their currency conversion.

If you have ever gone on Google search and run a currency conversion, you know that you can make a number of combinations to generate a currency conversion.

While coding out the full extent of Google’s allowable types would be far too complex and perhaps, dare I say, boring, we can provide a little help. Here is what we can do to support user input variation:

  1. Allow for any number before the currency code section.  E.g. 1 or 1,110,00 or $2300.00.
  2. Allow for the use of commas or no commas in the amount that users input. E.g. 1,000,000,000.00 or even mistakes 1,1,1,222,1,.00.
  3. Provide some spacing flexibility between:
    1. The amount and the currency code section. E.g. 20     AUD:USD or 20AUD:USD.
    2. The source currency code and the colon ( Up to 3 spaces should be enough). E.g. 20AUD :USD or 20AUD   :USD or 20AUD:USD.
    3. The colon and the destination currency code (Again, up to 3 spaces should be adequate). E.g. 20AUD: USD or 20AUD:   USD or 20AUD:USD
  4. Permit lowercase currency code or mixed case code. It costs us nothing to convert everything using the toUpperCase() JavaScript method. E.g. 20aud:UsD.

What will generate an error

On the other hand, there are some necessary items for us to send to the API in order for it to respond successfully with currency conversion. This means we should handle:

  1. Missing number. No number no conversion. Error e.g. /xe or /xe AUD:EUR
  2. Multiple decimal places. It is hard for us to guess where the user intended to add their decimal place so we need to return an error here. Error e.g. 2,333.21.24 or E.g. 2..34.561.01.
  3. Ridonculous amount. 🤯 Extreme amounts may be difficult for the API to handle are likely someone is being a little silly. We should respond in kind. Error e.g. 1126545465165198998118991981891.1656116165165156165165161651165
  4. Non-3 letter currency codes. All currency codes are 3 letters in length. Error e.g. 2A:USD or 4AUD:US
  5. Missing source and destination currency code or colon. If we don’t have a source or a destination code we can’t convert anything. Error e.g. 2:EUR or 2AUD or 2AUD:.
  6. Erroneous currency codes. We should check with our stored CurrencyCodes list before we waste valuable requests with the Currency Exchange API. Error e.g. 2XXX:USD or 2AUD:YYY.

Setting up the code

We will create the validateAndRetrieveCurrenciesAndAmount(text) function to handle our validation. This will be called from the attemptConversion() function after it receives the text from the /xe slash command.

Inside our validation function, we will extract our amount and currencies separately. This is because they require us to look at different things to ensure that they are accurate and ready to be sent to the API. This also helps us vary the spacing between the amount and the currency codes should they add a space.

It is much less costly and more efficient for us to run validation Apps Script-side rather than lose a request credit and let the API handle the error.

If we discover an error in the user’s input, we will return a text string to then containing information about the nature of the error. We will also include our instruction information contained in the errorInstructions variable.

If the user successfully enters their currency code, then our validation function will return an object containing the amount as a float, the source currency code and the destination currency code.

conversion = {source, destination, amount}

Regular Expressions

We will be using a variety of regular expression rules to achieve the majority of our validation here.

The Creator Of Regular Expressions
Regular Expressions were invented by Stephen Kleene, a known Priest of  Silencio, who designed the syntax to be rendered instantly forgettable if attempted to be learnt.

Because they can be a little tricky we will explain them here in a little more detail:

  • Extract the amount: /([\d.,]+)/:
    • [] – Indicates a character class or range to look for.
    • \d – Search for any digit.
    • ., – Search for any decimal (.) or comma (,)
    • () – Ensures that all elements are captured in a group where we can apply a quantifier to it like we have with the plus symbol.
    • + – matches one or more occurrences of the selected characters.
  • All periods or decimal symbols: /\./g:
    • \. – Search for a period.
    • /g – The global flag matching all occurrences of the selected search.
  • From and to currency code range: /[A-Za-z]{3}[\s]{0,3}:[\s]{0,3}[A-Za-z]{3}/
    • [A-Za-z] – Character class searching for any character within the alphabet with either upper or lower case.
    • {3} – Curly braces indicate a match of a specific number of times. If the braces have one argument it must strictly meet that number of occurrences.
    • [\s] – Character class search for spaces.
    • {0,3} – Matching a range of the preceding character or character class between two values.
    • : – Match a colon.
  • Get each currency code: /[A-Za-z]{3}/g:
    • [A-Za-z]{3}– The 3-letter code containing any letter from A to Z in any case.
    • /g -Any occurrence of the selected search item.

Video 3

The Code – SlashCommands.gs

attemptConversion()

Remove the placemarker: return xe text = "${text}".

Add:

 

validateAndRetrieveCurrenciesAndAmount(text)

Add the following function.

 

4. Connecting /xe slash command to the API and validation

Now we finally get to deploy our /xe slash command and get some results.

First, we need to update the returned item in our attemptConversion() function with the currencyConversion() function (see code below).

The currency conversion function will call the Exchange Rate API via our CurrencyAPI().convertCurrency() method. If successful, it will return the currency based on the inputs we have validated and send it as part of the payload to the API.

We could simply return a value (e.g. xe/ 10AUD:USD = 6.19865 ) but that does not provide a lot of context for our users instead we want to provide something with a bit more valuable that will include:

  • The returned result: 10 AUD = 6.19865 USD
  • 1 source value = destination value: 1 AUD = 0.619865 USD
  • 1 destination value = source value: 1 USD = 1.613254 AUD
  • The date the exchange rate was found: (Last updated: 2022-10-16)

Convert a currency inside a Google Chat Space Example

We can retrieve all but one bit of these from the object that is returned from our request:

The only thing we need to work out is the conversion of 1 destination value base to the source. We can do this by dividing 1 by the exchange rate.

1/result.info.rate

However, there is a spanner in our works…

spanner in the works

JavaScript Decimal Rounding Errors

The Problem

Our exchange rate returns a value up to 6 decimal places (e.g. 1.123456). This is more than enough to get a fine-grained indication of the exchange rate. Besides, it would look pretty message with a huge string of trailing decimal digits.

A problem arises in Javascript when we try and round up a value using the JavaScript toFixed() method.

Let’s say we have the number, 5.5555555, and we want to round up from 7 decimal places to 6. Our primary school education taught us that this should be 5.555556. However, using the toFixed() method we get. 5.555555. If we were to increase the number in the seventh decimal position to 6, 7, 8, or 9 all would be right in the world and it will round up as expected.

The Solution

How do we resolve this?

I found a really good solution shared by George Birbilis in StackOverflow. It does, however, warrant some explanation. Here is my version of the code:

+(Math.round(Number(weirdNum + "e+6")) + "e-6")

The ‘e’ here represents the exponent value. You will often see this when you are logging a huge number in JavaScript. It’s a kind of short-hand version.

For example, 5e6 would be:

= 5 * 10^6  (or to be more granular 5 * 10^+6)
= 5 * 10 * 10 * 10 * 10 * 10
= 5 * 1,000,000
= 5,000,000

So when we convert our weirdNumber variable plus “e+6”  with the Number constructor we are moving it left 6 decimal places.

= Number(weirdNum + “e+6”)
= Number(5.5555555 + “e+6”)
= Number(“5.5555555e+6”)
= 5555555.5

Now we can use the JavaScript Math.round() method to round the last decimal place to the correct value.

= Math.round(5555555.5)

= 5,555,556

Next, we need to convert the number back to the correct decimal value by reversing the exponent value we set:

= +(5,555,556 + “e-6”)

Note the plus symbol at the start of the braces, this is a sneaky way of conversing an exponent number text string to a number.

Video 4

Video released 19 Oct 2022.

The Code

SlashCommands.gs

In the attemptConversion(text) function replace:
return xe text = "${(typeof conversion === "string")? conversion: JSON.stringify(conversion)}"
with
return currencyConversion(conversion);
currencyConversion()

 

If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.

5. A Google Chat App Card for the list of currency codes

There are hundreds of currency codes that the users may wish to draw from and we can’t expect them to memorise them all. The easiest approach we have to support our users here is to provide them with a /xe-list slash command in their Google Chat or Space.

When the user returns the slash command, they will get a stylised card response:

Google Chat App Currency Converter xe-list slash command example

This looks a lot nicer than listing all the currency codes in a message.

This time around instead of returning a text object property we will be returning a card version 2 property.

Cards version 2 JSON

We will need to create a JSON to send to the Chat API to construct our card.

The card contains a header property and a section property.

In our project, we style our header with a title, subtitle and image. Also, note that cards can contain stylable headers as well if you choose to use them.

The section sub-object contains an array of all of the sections that you want to add. Sections provide visual separation in the card and are useful for us to separate our currency codes by letters of the alphabet for ease of reading.

Inside each section, you can add a number of widgets set as an array. There are heaps of widgets to choose from that we noted in our Google Chat App for Developers tutorial.

From the widgets list, we used the Decorated Text widget. It has a wide range of uses from button clicks and better styling to adding icons and even switch controls.

We only needed to use the top label property to add our letter and then generate our list of currency codes and their descriptions for that letter using the text property.

Image link

If you want to use the same image in your project you can find it here:

https://images.unsplash.com/photo-1599930113854-d6d7fd521f10?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=880&q=80

The image is by globe maker, Gaël Gaborel.

Video 5

Video released 22 Oct 2022.

The Code

Code.gs – onMessage()

Add a third switch option for /xe-list

Don’t forget that you will need to go to your GCP console for your project. Select APIs and Services. Then scroll down to find your Chat API.

In the Chat API, select configuration. Scroll down to the Slash commands select and add a new slash command.

The details will be:

  • Name: /xe-list
  • Command ID: 3
  • Description: List of all currency conversion codes.

Select ‘Done’ and then save the configuration.

CurrencyCardList.gs

Create a new file called CurrencyCardList.gs. Here you will add the following function.

createListCardResponse()

 

Conclusion

That wraps up our Currency Converter Google Chat App built-in Google Apps Script.

There are a bunch of further directions we could go with the chatbot. We could add an API key input dialogue for each user to add their own API key for the Exchange Rage API.

Alternatively, we could create a customisation dialogue that will allow the user to create a custom display format and input type for their specific region. After all, not all currencies are written the same in different countries.

Another thing we could do is to create a dialogue when users just add /xe instead of appending an amount, source and destination code. Then we could rely on selection boxes for users to choose their currencies, and even add a date.

What else can you think of to improve this project? I would love to hear in the description below.

This was an enormous project to put together taking up several months of preparation, content writing and video creation. I hope you got something out of it.

If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.

~Yagi

Google Chat Apps for Google Apps Script Developers

In this article, we will look at Google Chat Apps and go over some of the basics of developing a chat app with Google Apps Script.

Note that Chat Apps are currently only available to Google Workspace paid accounts and not standard ‘@gmail’ consumer accounts.

What are Google Chat Apps?

All about Google Chat Apps YouTube Video
Click to go to the video!

Google Chat is a business-level messaging tool for Google Workspace that allows you to chat one-on-one and in groups called Spaces within your business and even with clients and contractors outside of your domain.

Its integrations with Google Workspace tools like Google sheets, docs and slides right inside chat along with a Google Task tab and a convenient file library tab make it a really handy business tool.

But one thing that is often overlooked is that you can add Chat Apps or Chat Bots to your Google Chat Spaces or DM a chat app directly to accomplish tasks conveniently.

There are hundreds of 3rd party Chat App integrations for you to choose from. Anything from project management to customer support and more.

Google Chat Apps Available

Chat apps can:

Continue reading “Google Chat Apps for Google Apps Script Developers”

Get Hidden or Visible Google Sheet Tabs with Google Apps Script

Based on a viewer’s recent question, here is how you can get a list of all hidden or visible Google Sheet tabs with Google Apps Script.

You can integrate these scripts into your own projects.

The Video

Continue reading “Get Hidden or Visible Google Sheet Tabs with Google Apps Script”

Duplicate Filter Views in Selected Google Sheet Tabs with Google Apps Script

While there is not way to directly duplicate Filter Views into other sheet tabs in Google Sheets we can do this with a little bit of Google Apps Script magic.

In this tutorial, we will walk through how to duplicate all filter views from a source Google Sheets tab and duplicate them into selected sheets tab.

We’ll start off with an example sheet to better understand what we are going to achieve and then share the code along with a quick-use guide for those of you who want to to just get in and use the script in your own project.

Next we will provide a video tutorial walking through how I built the script and wrap everything up with some bonus scripts to extract different parts of the code. If you get to this stage you should have a better understanding on how to work with Filter Views programmatically.

Let’s dive in!

The Example Google Sheet

The best way of following how the code works is with an example.

In our example sheet we have 6 different stores in six different Google Sheets tabs. Each store contains the same headers; Date, Company, Name, Notes, Type/Specialty, Quoted, Actual.

We also have a NOTES sheet tab that provides instructions for the sheet.

If you want to play along, you can grab the example sheet from the link below:

Duplicate Filter View – Google Sheet Starter

Aim

We want to create a set of matching Filter Views for each of our stores without having to manually duplicate each one by hand in the sheet tab.

We have five filter views that we want to include in each of our company sheet tabs.

List of filter views in a Google Sheet tab

Of course, we don’t want to add filter views to our NOTES sheet tab.

The Problem

While we can create individual filter views inside a tab, we can’t migrate those filter views over to existing sheet tabs. So the only Google Sheets alternative is to manually update each sheet tab with our list of filter views that we want to add.

Another problem then arises when we need to make a modification to one or more of our filter views. All tabs have to be then modified by hand, increasing the chance of mistakes and significantly increase a big old case of boring.

Imagine if you had 50 different sheet tabs for 50 different businesses. That would be a nightmare to create and update.

The Solution

We will only create and update filter views in our first business sheet tab that we have called ‘MAIN’ in our example. Then we will use some Google Apps Script to update all the other business sheet tabs with the filter views.

One thing that is important to keep in mind when the script is being built is to ensure that the filter view length changes for each sheet tab to accommodate the length of rows in each business sheet tab as they change.

If we need to make adjustments to our filter views and then update all business sheet tabs, we will first need to remove the existing filter views in all but the origin sheet tab that have the same name as the origin filter views (for us, “MAIN” tab views) before updating them. Otherwise we will generate an increasingly long list of filter views that all have the same view name.

Also, we probably don’t want other users to be able to ‘accidentally’ edit our Apps Script Code for the Google Sheet, so we will store the scrip unbound in a separate Apps Script file.

Here’s the code.

The Duplicate Filter Views Code

To keep things neat and tidy we will keep our duplicate filter view code in a new Google Script (*.gs) file. In our main Code.gs file I’ll add some sample code to add in all of our information needed to run the script.

Keep in mind that you could call the duplicate filter views script on its own like I have below or part of a larger process in your own project.

For your own project, you will need to create the duplicateFilterViews.gs file and copy and paste in the script. Optionally you can add the Code.gs file to run the script like I have or build your own.

Note! Unless your Google Sheets project is exclusively for you or a highly trusted team, I would recommend creating a separate Google Apps Script Project. 

Code.gs

Quick Use Guide

Add the Google Sheets Advance Service

You will need to access the Advanced Google Sheets Service for Apps Script before continuing. To do this select the Add a service plus button from the Services menu then scroll through the list of services until you find the Google Sheets serivce. Select it and click Add.

selecting Google Sheets Advance Services in Google Apps Script

Setting up your reference data

The runsies_duplicateFilterView() function for our example contains all of the data we need to run our script.

We first list all of our variables:

  • ssID (string) – The Spreadsheet ID for the Google Sheet you are working on found in the URL of the document.

    URL for duplicate filter views Google Sheet
    click to Expand!
  • sourceSheetName (string) – The name of the Google Sheet tab that contains the Filter Views that you want to duplicate. For our example this is the “MAIN” sheet tab.
    Main source Sheet tab for duplicate filter views Google Sheet
  • destinationTabList (Object) – this Object contains two properties:
    • areExcludedTabs (boolean) – Are you providing a list of all sheet tabs you want to exclude from duplicating the filter views? If so, mark true. This is probably the most common case. Otherwise mark it false if you are providing a list of all sheet tabs that you want to include. If so, mark false.
      We chose true in our example so we only have to add one item (excluding the ‘NOTES’ tab)…cause we lazy.
    • tabNames (array) – An array of all the sheet tab included or excluded depending on your choice in areExcludedTabs. Don’t add the source sheet tab to this list.
      • E.g. of included list:["Sheet 2", "Sheet 3", "Sheet 4", "Sheet 5", "Sheet 6"]
        Inclusion destination Sheet tabs for duplicate filter views Google Sheet
      • E.g. of excluded list: ["Notes"]

Finally we run the duplicateFilterViews(ssID, sourceSheetName, destinationTabList). Note that we have included the three constant variables as our arguments for the function.

Paste in the duplicateFilterViews.gs code and run

After you have updated your Code.gs file and added the script to your newly created duplicateFilterView.gs file (script below). Save the file and select run from the menu bar.

Once the script has run, you can check our Google Sheet tabs to see that all filter views have been duplicated successfully.

Looking to learn more about Google Apps Scripts in a more structured format? Udemy has some great courses that can get you from the basics to a real Google Apps Script pro.

Got a more specific problem you need help with, but don’t have the time to develop the skills? Make an enquiry on my 'Hire me!' page. I occasionally pick up projects. Alternatively, Fiverr’s your best bet to find a skilled Google Apps Script developer to solve your problem quickly and professionally. *

*The above affiliate links have been carefully researched to get you to what you specifically need. If you decide to click on one of these links it will cost you just the same as going to the site. If you decide to sign up, I just get a little pocket money to help pay for the costs of running this website.

duplicateFilterViews.gs

Copy and paste the script below into your own project. I recommend adding it to a separate duplicateFilterViews.gs file for easier management.

Using the Google Sheets Advanced Service for Filter Views

We need to approach the Google Sheets Advance Service API quite differently to how we use the SpreadsheetApp class. The advance service requires us to retrieve and update an object or array-object to carry out our processes.

This means that we need to test the object directory path so we can see where locations are for us to find or update what we need. I’ve left this testing phase out of this tutorial, but this is something you will need to do.

For our project we need to use the Sheet.Spreadsheet resource. From here we will either get our Filter View data for the spreadsheet or send a batch update to make bulk changes to the sheet.

Get our Filter View Data

We retrieve our list of all filter views only one time in our getAllFilterViews() function.

Now we can simply get a list of all the date in the entire spreadsheet by using the get method and apply the selected spreadsheet ID like this:

Sheets.Spreadsheets.get(ssID)

Get just filter view field data

However, this is pretty wasteful and generates a bulky data set. Instead we can narrow in on the spreadsheets list of filter views by adding some some optional arguments to our get request.

Here, we use the “fields” property to tell the API what fields that we only want to retrieve. For us, this is our filter views. Our filter views are applied to each of the sheets in our spreadsheet so we must create the path “sheets/filterViews”. Our code then looks like this:

This will return our data containing all the filter views.

Once retrieved we can follow the property tree or iterate through the sheets, and filter view arrays. In the code above we immediately reduce our data down to just the array of all of our sheets.

Batch update our Filter View Data

We update our filter view data on two occasions in our script. First when we delete all the duplicates in our destination sheet tabs and then to add our new duplicate filter data to our destination sheet tabs.

To do this we use the batchUpdate method. This method takes two parameters:

  1. The resource containing the requests from us to update the filter views on the spreadsheet.
    1. requests – this is our list of requests to update our data. It will contain an array of objects where each object contains the data that we wish to update.
      1. Instruction – Each update object starts off with an instruction that is known as a ‘request’. You can find a list of all available requests here.
  2. The spreadsheet ID.

Delete a filter view

To delete a filter view we use the deleteFilterView request. This requests is pretty simple all it requires is for us to provide the filter id of the item we want to delete. You can see it in use in lines 133-136 of the DuplicateFilterView.gs file code above.

Add a Filter View

Adding a filter view is much more complicated. Well… it would be if we were not just using an existing filter view and making a few modifications to it.

To add a filter view we use the the addFilterView request. This requests sets the filter and then an object containing all the data we need to build the object.

{ 'addFilterView': { filter: Object of filter view data } }

You can see how we added this on line 175 of our duplicateFilterViews.gs file.

For our tutorial we didn’t need to build the view in its entirety, we just needed to:

  • remove the existing id of the view (You shouldn’t have one, because it will be added for you)
  • update the range > sheet ID to the new destination id
  • update the end row to match the current depth of the data in the destination sheet

Lines 177-187 of DuplicateFilterView.gs

The Video Tutorial

Here’s the link to the Starter Sheet for you to follow along:

Duplicate Filter View – Google Sheet Starter

 

If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.

Bonus Functions

Maybe you only want to get a list of all of your filter views in a spreadsheet or all the filter views for a selected sheet tab. Perhaps you just want to delete all the non-source tab filter views you created.

Check out the following three functions to give you some ideas on how you might use the duplicateFilterViews.gs file to achieve this.

I have appended each function name with runsies_ but you can rename and rebuild them how you want.

If you have been playing along, you can add them to the Code.gs file to run them.

runsies_showAllFilterViews()

This function takes your spreadsheet ID and runs the showAllFilterViews() function. The function returns a full list of all the filter views in all of your sheet tabs for your selected Google Sheet spreadsheet.

We then log the results, but you may wish to use them in other ways.

Keep in mind that the results will most likely be larger than what the console will contain, but logging the result will give you a good idea on how the Array of filter view objects for each tab is stored.

runsies_selectedSheetFilterViews()

This function gets all the filter views from all sheets and then returns just the data for the selected source sheet. In our case, this in ‘MAIN’, but you can change this to what ever sheet tab you are looking for.

The results are then logged. The filterViews property will give you an array of all of the views in the selected tab.

runsies_deleteAllCopiedFilterViews()

If you no longer wish to have the duplicates of the source filter views in your destination sheet tabs, you can use this function to remove them.

You should put in all the same arguments in this function that you had for your runsies_duplicateFilterViews() function.

 

If you have found the tutorial helpful, why not shout me a coffee ☕? I'd really appreciate it.

Happy Coding!

 

~Yagi

 

%d bloggers like this: