Clear and Set Conditional Formatting Rules to a Specific Range in Google Sheets with Apps Script

I’ve created a small (pseudo) class that more easily clears and creates conditional formatting rules in a Google Sheet tab with Google Apps Script.

Why?

Well in Google Apps Script, conditional formatting rules are all or nothing.

You can only ever set, get or clear ALL rules in a specified Google Sheet tab.

So if you add a single rule to a sheet tab, all existing rules will be removed.

This means that each time you need to clear a rule or a portion of a rule or add in a new rule, you need to rebuild the entire rule set for that sheet tab.

It is an unpleasant experience.

The script below simplifies this process into some common clear and create processes for your conditional formatting.

Let me know in the comments below if you have a suggestion for another method for the class.

One last thing.

If you want to understand what is going on with the code (You are my kind of peeps), check out the video tutorial series.

The Code: Range_ConditionalFormatting()

To add this script to your own projects, I recommend that you create a new Google Apps Script file (page) and paste the code in there.

Check out the chapters below on how to use the class.

Note! Square brackets around parameters indicate optional parameters.

Class

The pseudo-class Range_ConditionalFormatting(sheet) tales one argument:

Video link: Range_ConditionalFormatting(sheet) 

Methods

Method Return Type
clearRule()
Clears a rule or rules by a single range or array or ranges, based on 3 clearing approaches.
setRule()
Sets a rule or rules while maintaining the existing rules in the Sheet tab.

clearRule(rangeOrRanges, [clearType])

Clears the conditional formatting rules in a Google Sheet tab by the selected range or ranges and clear type while maintaining the existing conditional formatting rules in the Google Sheet tab.

Video link: clearRule method

Parameters

Name Optional Type Description
rangeOrRanges Range or Range Array A SpreadsheetApp.Range or array of ranges that will be the target locations to clear.
clearType Number The way the method should clear the range (see below)

Default is clearType = 0

Clear types

  • 0 – Clears any conditional formatting rule that exactly matches the range.
  • 1 – Clears any conditional formatting rule that has a range within the target range.
  • 2 – Clears any conditional formatting rule or portions of the range of a rule that overlap the target range.

Examples

clearRule(range) – Single range and no optional clear type

Clears a conditional formatting range that exactly matches the single range provided.

Video link: clearRule(ranges) – Ranges and no optional clear type

clearRule(ranges) – Multiple ranges and no optional clear type

Clears the conditional formatting that exactly matches multiple ranges.

 

clearRule(range, clearType = 0) – Single range with clear type zero- Exact match

Clears a conditional formatting range that exactly matches the array of ranges provided. Clear type zero (0) is the default clear type.

Video link: clearRule(ranges, 0) – Exact match

clearRule(ranges, clearType = 0) – Multiple ranges with clear type zero – Exact match

Clears the conditional formatting that exactly matches multiple ranges.

clearRule(range, clearType = 1) – Single range with clear type one – Within range

Clears a conditional formatting rule range that has a range equal to or within the target range.

Video link: clearRule(ranges, 1) – Within range

clearRule(ranges, clearType = 1) – Multiple ranges with clear type zero- Within range

Clears all conditional formatting rule ranges equal to or within the target array of ranges.

clearRule(range, clearType = 2) – Single range with clear type one – Overlaps

Clears a conditional formatting rule range that has a range equal to or within the target range or rebuilds the range where any range overlaps the target range removing that portion of the range.

Video link: clearRule(ranges, 2) – Overlapping ranges

clearRule(ranges, clearType = 2) – Multiple ranges with clear type zero- Overlaps

Clears all conditional formatting rule ranges equal to or within the target array of ranges or rebuilds the range where any range overlaps the target range removing that portion of the range.

setRule(rules, [position])

The setRule method adds a conditional formatting rule or rules to an existing Google Sheet tab. It does not remove any existing rules in the selected tab.

The method has an optional position parameter that allows the user to customise where they wish to order the rule in relation to the existing rules on the Sheet tab.

Video link: setRule method

Parameters

Name Optional Type Description
rules Conditional Formatting Rules A

array of objects. This is an array of rules built with the Apps Script conditional formatting rule builder.

position Number The position of the new rule in the existing set of rules.

Default is position = -1, or the bottom of the rules array.

A position of zero (0) sets the rule to the top of the array set.

Positive numbers apply position up to max length of the rule set.

-1 for end of the rule

Rules with negative numbers are position from the last rule in reverse order up to zero.

Examples

Video Tutorial Series

You can check out the playlist for Conditional formatting here.

Apps Script – Google Sheets Conditional Formatting Playlist

The video tutorials:

  1. Clear Conditional Formatting Rules by Exact Match in Google Sheets with Apps Script
  2. Clear Conditional Formatting Rules Within a Range in Google Sheets with Apps Script
  3. Clear Conditional Formatting Rules that Overlap a Target Range in Google Sheets with Apps Script
  4. Add Conditional Formatting Rules to a Google Sheet Tab with Apps Script

Conclusion

Being such a short pseudo-class it is hardly worth slowing down your script by making this into a library. I recommend you just add it to your existing project for simplicity and performance.

If you think there are any other methods worth adding, please let me know in the comments.

I would also love to hear how you used this in your own projects.

Create and Publish a Google Workspace Add-on with Apps Script Course

Need help with Google Workspace development?

Go something to solve bigger than Chat GPT?

I can help you with all of your Google Workspace development needs, from custom app development to integrations and security. I have a proven track record of success in helping businesses of all sizes get the most out of Google Workspace.

Schedule a free consultation today to discuss your needs and get started or learn more about our services here.

~Yagi.

Add the Editor’s Email when they Tick the Check Box in Google Sheets with Apps Script

This tutorial is for Google Workspace Domain accounts.

Recently, I was a guest interviewee at a Google Workspace Developer Summit in Singapore and an attendee asked me how they could automatically add the editor’s email to an adjacent cell when the user checks a check box in Google Sheets.

This can be incredibly handy for project managers to see when a user completes a task or, at a glance, who edited a row.

Of course, there are some simple ways of doing this out-of-the-box within Google Sheets.

  1. A simple right-click > Show edit history on any cell can reveal who has edited the cell in the past.
    Show cell history in Google Sheets
  2. If you want a more detailed history of edits on your Google Sheet workbook then you can always select the version history button in the top right of your Sheet.

    Google Sheets Version History
    The ‘clock’ icon here opens the version history page.

The problem with these options is that it is not there on the screen for the user to quickly see who edited what line.

In this tutorial, we are going to use some Google Apps Script magic to automatically add the editor’s email to the row when they click that checkbox.

Let’s dive in!

Continue reading “Add the Editor’s Email when they Tick the Check Box in Google Sheets with Apps Script”

Add the Current Date to a Sheet When Data Is Added So That The Date Does Not Change(Static) – Google Sheets (Updated July 2023)

Google Sheets, Google Apps Script: onEdit

You’ve probably come across the problem where you need to know when a piece of data has been added to your spreadsheet. You probably have been equally frustrated that there is no out-of-the-box function that will do just this.

You’ve tried TODAY() and NOW(), but they change dynamically. What you really need here is something that does not change.

Let’s look at two workarounds that can help you out with this problem.

Continue reading “Add the Current Date to a Sheet When Data Is Added So That The Date Does Not Change(Static) – Google Sheets (Updated July 2023)”

Creating an embedded interactive Chain Story app with Google Apps Script and Google Sheets

Google Apps Script: WebApp, HtmlService, LockService; Google Sheets

In this tutorial, we are going to create an interactive story chain app that we can embed into a Google Site or your own site like WordPress.

What’s a chain story, Yagi? 

Maybe you did this in school. Someone wrote the first part of a story. You then gave that story to someone else to continue writing. They then pass the story on to someone else to write the next part. And so on and so forth. In the end, the story is read out and everyone laughs at the direction the story went – except that one kid silently raging over their lack of control of the narrative.

Why are we making this? How’s it going to help me?

Well, for one, I thought it would be fun. More importantly, this will allow us to have a look at how Google Apps Scripts communicates client to server-side and vice versa in a little more advanced environment than our previous tutorial. It will also give us an opportunity to look at some more parts of Google Apps Script as they relate to creating a WebApp.

Our chain story WebApp tutorial will also give us an opportunity to look at some of the pitfalls of using WebaApp. Particularly when using the execute as me permissions. Finally, this will then launch us into our follow-up tutorial on updating the WebApp to execute as the user rather than me, the owner of the app.

This tutorial is the second part of the WebApp series. However, if you can read a bit of JS, CSS and HTML, you should be able to follow along and if you get stuck you can always go back to the first tutorial:

Google Apps Script: How to create a basic interactive interface with Web Apps

Let’s get started…

The Example: An interactive chain story

Embedded below is our interactive Chain Story web app. If you are feeling creative, read the story so far and then add your part to the story. It has been written by readers just like you:

Continue reading “Creating an embedded interactive Chain Story app with Google Apps Script and Google Sheets”

Creating Unique Ranges from 2D Arrays in Google Apps Script

Google Apps Script, Google Sheets, Javascript 

If you have ever done any work in Google Sheets you might have come across the incredibly useful UNIQUE function. This function can take a single row or multiple rows and generate a list of unique cell values.

UNIQUE demo Google Sheets

Sometime you might have a use case where you need to replicate the UNIQUE functionality in Google Apps Script. Maybe you are drawing in data from another source like an API, BigQuery or a database, or presenting your unique data in another format.

Whatever the case, knowing how to to create a unique array from a 1-dimensional array or a 2-dimensional array is an important part of your toolkit as a coding goat 🐐. This tutorial will look at how to create this with modern Javascript that is incorporated into the Google Apps Script language. And of course, we’ll focus our tutorial more on a Google Apps Script because that’s kinda our thing.

We’ll start off with a very basic example of creating a unique array from a 1-dimensional array in our code:

UNIQUE Array generated from a 1d array in GAS

…and then build ourselves up to a final example by grabbing multi-column range of Google Sheet data from which we create a unique list and then display the total sum corresponding to each unique cell value in each of our associated unique columns. Something like this:

UNIQUE 2-Array of multiple columns with result set in GAS
Click to Expand!

As we go through our examples I’ll display the runtime of the entire code. Runtime is not a perfect indicator of the performance of the script there are other factors that will influence the runtime, but it will do for our purposes. I think you will be surprised by how fast these scripts run.

Before we get started, let’s take a quick look at the sample data…

Continue reading “Creating Unique Ranges from 2D Arrays in Google Apps Script”