Blog Feed

Find and Hide Rows in Google Sheets with Apps Script

Using the Spreadsheet App Class’ Text Finder Class to find and hide rows in Google Sheets containing target text in a cell can be a fast way to hide values. In many situations, this may be a faster way to hide rows based on cell value in Google Sheets with Google Apps Script than iterating through a range and extracting rows.

In this tutorial, we will cover 3 approaches to using the Text Finder class to hide rows. Each may be useful in its own circumstances.

This tutorial accompanies the YouTube video series of the same name. You can find the links to each of the related videos in each of the sections along with the starter Google Sheets so that you can play along.

V1 – Basic Find and Hide Rows based on cell values in Google Sheets

Starter Sheet

Version 1 – Starter Sheet

The Video

https://youtu.be/alI2f7w7xjU

The Code

Unlike when formatting rows and cell activation, – as we did in the previous tutorial – our fasted approach here is to hide and unhide sheets while looping through all the found cells.

In this basic approach, our function contains 3 parameters:

  • text – The text to search.
  • sheetName – The sheet name to search.
  • isHide – An optional argument set to true by default to hide values or false manually to unhide them.

Lines 10-11Β – We first collected our current Google Sheet workbook and then select the sheet tab we will be working in.

Lines 13-14 –Β Then we use the Text Finder class in the Spreadsheets App to search for our target text and then use the findAll() method to get an array constructor of all the found value cell ranges. You can learn more about this in the first tutorial in this series here:

Find All Values in Google Sheets with Apps Script

Line 16 –Β Next we iterate through each found row with a JavaScript forEach() loop.

Line 17 – On each iteration, we collect the row number. We do the same thing here in our previous tutorial when activating and formatting entire rows.

Lines 19-23 –Β  Lastly we need to check if the user has set isHide to false to show the rows or true (or not used) to hide the row. We then call the sheet and apply either the Spreadsheets Apps Hide Rows (hideRows()) method or (showRows()) Show Rows method. These methods can take a single row as an argument. We provide this with the row variable.

This is a quick and easy solution to understand. However, it does not perform well with a large dataset. It will also try and hide rows multiple times when a found cell is on the same row as a previously found cell.

The function, just like the other two examples, can be called from another function with:

hideAllRowsWithVal(text, sheetName, boolean)

e.g.:

hideAllRowsWithVal("koala", "Sheet1", true)

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

V2 – Find and Hide Rows based on cell values in Google Sheets with Range Grouping to improve performance

Starter Sheet

Version 2 – Starter Sheet

The Video

https://youtu.be/CeWUAOK7Ui8

Released Monday 12 Feb 2023. Subscribe (Top right) to get a notification for when this video comes out.Β 

The Code

In larger, ranges we might have a lot of situations where our found text is on multiple adjacent rows.

Find and hide rows by grouping ranges in Google Sheets with Apps Script

In the image above, we can see that rows 30 and 31, 38-43, and 46-49 can all be batched together into a single range.

Furthermore, rows with the found text (Koala) on the same row can be ignored, the consecutive times that they are found.

Let’s go ahead and fix our code to make it more efficient.

Note that lines 9-16 of the code are the same as the previous function. Refer to this for an explanation.

The Hide Range METHOD

Line 22 – After we have collected our ranges of found rows we will create a hideRange() method. This will either hide or show the range based on the isHide argument.

This function takes a single object parameter that contains a start row and a number of rows.

Lines 24 – 26 – Unlike the previous version, we use the Hide Rows and Show Rows extra parameter to include the number of rows deep to hide.

Row Range variable

Lines 32 – 35 –Β This mutable variable stores the start row and row depth as we collected each range of rows to hide in our sheet.

Iterate through all cells

Line 37 –Β Here, we start the forEach loop that iterates through each found cell range. We include the index (idx) in our arguments in our arrow function as well here.

Line 39 –Β Next, we grab the row number with the Get Row (getRow()) method.

Line 40 –Β Then we get the next possible row in the current range collection by adding the start row with the row depth. This will be used in a moment ot compare against the currently iterated row.

On the first iteration

Lines 42-46 – On our first loop through our found cells, all we need to do is add our first found row and add one to our depth.

There is another cell on the same row

Lines 47-51 – If there is another cell on the same row, then we don’t need to do anything and we simply return the function for that iteration.

There is a cell directly below the previous one

Lines 52-55 – If the next found row is only one cell down (adjacent), then we just want to add one to the number of rows of the existing rowRange variable.

Lines 57-60 –Β If the row is the last found row, then we can run the hideRange function on our update range set.

A new range begins

If the next found row is not directly below the previous one. We need to:

  1. Line 63 –Β Run the hideRange on the current rowRange variable set.
  2. Lines 65-66 – Reset the rowRange variable adding in the current row to the start range and one to the depth.

Lines 69-71 – Again, if we are on the last found row, we can just run hideRow to end the loop.

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

 

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.

V3 – Find and Hide Rows based on cell values in Google Sheets using the Google Sheets Advanced Service API and Range Grouping

The Video

Released Thursday 13 Feb 2023. Subscribe (Top right) to get a notification when this video comes out.Β 

Starter Sheet

Version 3 – Starter Sheet

The Code

I found version two to be remarkably efficient. However, if you want to do a lot of editing to the sheet tab then you might want to consider using the Google Apps Script Advanced Sheet Service API.

Main Variables

We need to add a few more variables to our main variables here.

Line 12 –Β We will need to get the spreadsheet ID to use in our batch update.

Line 13 –Β The sheet name does not work the same as an identifier in the advanced service, so we will need to extract the sheet ID too.

A request list

Line 21 –Β The Sheets batch request property requires a list of requests as its value. Here we will store an array of all the requests that we want to batch together to hide each row range of the Google Sheet.

Update Dimension Properties

Line 27 –Β The appendRequest(setRange) function pushes a new request to the requests property.

When hiding and displaying rows or columns in a Google Sheet with the Advanced Service we are updating a dimension property. These properties can be a number of different field types, but for us, we want to hide rows.

Let’sΒ  take another look at the layout of this JSON object:

Lines 3-8 – The first sub-property is the rangeΒ object. This object requires a sheet ID. The dimension is either the columns or rows.

Then we need to set the start index. Note that the cell ranges will start from zero instead of 1. We must then subtract 1 from our start row to get the correct start index of our row range.

Finally, we set the end row. This will be one row after our desired end row. Think, ‘up to, but not including this row’.

Lines 9-11 –Β Next, we identify the property that we want to change. For hiding and showing rows this is the "hiddenByUser" property, where the value is a boolean. This conveniently fits with our ishide parameter.

Line 12 –Β Weirdly, we then need to declare that we are using the "hiddenByUser" property by adding it to the fields list.

Store the current row range

Lines 46-49 – Just like the previous version, we need to store each range before sending it to appendRequest(). Unlike the previous version, our last property is the end row rather than the number of rows.

Starting the loop

LinesΒ  52-54 –Now we can commence our loop through the found cells.

Here, the first task is to collect all the row numbers.

On the first iteration

Lines 56-60 – On the first loop of our cell array, we just want to add the current row number to the start and end row of rowRange.

If the next row is on the same row

Lines 61 – 65 –Β If we have more than one result on the same row we want to ignore it and return the current loop.

If its the next row below

Line 69 –Β We add one to our end row value in rowRange.

Lines 72-74 – If we are on our last found row, send it to appendRequest().

Create a new row range

Line 77 – If the current row is not the next row down then we send appendRequest() with our current rowRange.

Lines 79-80 – Next, we create a new rowRange.

Line 83-85 – If the current row is the last row in the array, we sent it to appendRequest().

The Batch request

Line 90.Β Here we use the batch request of the spreadsheet resource. The batch request takes an object with a requests property. This property, in turn, requires an array of JSON object requests.

For its second argument, we reference the Spreadsheet ID.

 

Some notes

If you know that there may not be any matches in your text finder then you might wish to add a return agent after the allOccurrences variable:

if(allOccurences.length === 0) return;

Another good measure might be to use a try/catch statement in the third version when running the batch call, just in case there is an error with the API server.

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

~ Yagi

 

 

Find and Select or Format rows in Google Sheets with Apps Script

In this tutorial, we create 3 Google Apps Script functions that are used to:

  1. Find and select the row containing the first or last value in a Google Sheets sheet tab.
  2. Find and select all rows containing the search value.
  3. Format all rows containing the search text.

You can grab a copy of the starter Google Sheet to play along here:

Find & Select or Format Rows – Tutorial

This tutorial accompanies the YouTube video of the same name:

https://youtu.be/Y7rnQT6qYiA

All functions are built to be run from another function, making it easy for you to integrate them into your own projects.

For our example, we will use the runies function for this purpose.

All three of theΒ  examples below take two arguments as parameters:

  • text – the search text.
  • sheetName – the Name of the selected sheet tab.

These functions rely on the Apps Script Spreadsheet App Text finder class to search for the target text within the range.

All examples search a selected sheet tab. However, you can easily modify the script to search a specific range or the entire Google Sheets workbook. You can learn more about how to do this here:

Find All Values in Google Sheets with Apps Script

Find and activate the first or last row in a Google Sheet with Apps Script

Lines 10-12 – In this scenario, we activate the first (findNext()) or last (findPrevious())found row based on a search item that can be found anywhere in the row. We then store this cell range in the cell variable.

Line 17 –Β  From the cell variable, we can select the Spreadsheet App Range getRow() method to get the row number of the cell.

Line 19-21 –Β Next, we can activate the range of the selected row using the activate method.

We set the entire range by using A1-notation here within a template literal (that is a string within backticks ()). In Google Sheets, we can set the full width of a sheet by leaving the last column value blank in the notation, for example:

A1:1 or even 1:1.

Incidentally, you can also select a portion of the width by including an end letter in the range, for example:

A1:K1 or in the script .getRange(A${row}:K${row}`)

You can learn more about selecting the first or last found values in this tutorial:

Find first, last or nth value in a Google Sheets range with Apps Script

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

Find and activate first row based on a search value in Google Sheets
Example finds the first instance of ‘Koala’ in the range and selects the row.

Find and activate all rows in a Google Sheet with Apps Script

In this example, we select all of the rows containing the target search value.

Line 13 –Β First, we modify the Text Finder variable to the findAll method and rename the variable. This will return an array of all the cells where the values are found as an array.

Lines 15-16 –Β Now, we can map over each item in the array creating a new array of ranges that contain A1-notation of the selected row.

Line 18 –Β Finally, we can use the Spreadsheet App Sheet Class getRangeList() method to collect all ranges in our array and then activate them.

Find and activate all rows based on a search value in Google Sheets
Finds and activates all rows in the range that contain ‘Koala’.

Find and format all rows in a Google Sheet with Apps Script

This last function is virtually the same as the previous one. However, we are doing something much more useful, we are programmatically updating the format of the selected rows.

Lines 18-21 – Using the getRangeList method, we can modify the formatting of any range in the list. In our example, we set the background of the row to a dark blue, changed the text colour to white and bolded the font.

Find and format all rows based on a search value in Google Sheets
Finds and formats all rows containing the search item ‘Koala’.

More formatting methods you can use.

Here is a list of common formatting methods that you can apply to a range list:

  1. Clear FormatclearFormat() – Clears the formatting of the selected range.
  2. Set background ColoursetBackgroundColor(colour) – Use CSS notation like hexadecimal colours, colour names or RGB colours
  3. Set font ColoursetFontColor(colour)– Use CSS notation like hexadecimal colours, colour names or RGB colours.
  4. Set font WeightsetFontWeight(type) – Either “bold” or “normal”.
  5. Set font Size= setFontSize(size) – The font size as a number.
  6. Set font StylesetFontStyle(style) – The style, e.g. “Helvetica”, “Poppins”.
  7. Set vertical alignmentsetVerticalAlignment(alignment) – “top”, “middle” or “bottom”.
  8. Set horizontal alignmentsetHorizontalAlignment(alignment) – “left”, “center”, “right”.
  9. Set text rotationsetTextRotation() – Sets the rotation of the text in each cell in degrees from the original horizontal plain.

In the next tutorial, we will cover how to hide and unhide rows based on found values in a range. The process is a little different, so well worth checking out.

Subscribe to get an email when the next tutorial in this series comes out or get regular updates on my latest tutorials.

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

~Yagi

GWAOw! 5 – Insert Special Characters by Sheets Help

In this episode of GWAOw!!! we look at Insert Special Characters by Sheets Help.

About Insert Special Characters for Google Sheets.

As the name suggests, the Insert Special Character Add-on allows you to access the complete list of special characters like maths symbols, shapes and arrows, currency symbols, dingbat and Greek and Coptic symbols from the sidebar of your Google sheets.

This is all accessible from the convenience of the sidebar within your selected Google Sheet.

Features

The Insert Special Character Google Workspace Add-on comes with some handy features. You can:

  1. Modify the colour and size of the characters before installing them.
    Modify colour and size before inserting special character into Google Sheet
  2. Insert Multiple characters into one cell.
    Insert multiple special characters into a single cell in Google Sheet
  3. Filter the character list by:
    1. Arrows
    2. Geometric Shapes
    3. Currencies
    4. Maths Symbols
    5. Dingbats
    6. Greek and Coptic Symbols
      Filter special characters lists in Google Sheets
  4. Use the search bar to search for a specific character.

Search for a special character in Google Sheets

Pricing

The add-on comes with a 7-day free trial followed by a very reasonable one-time $7 purchase, but…I spoke to Adam from Sheets Help and managed to get you 20% off.

I don’t know how long the offer will last so I recommend that if you find this Add-on useful, take advantage of the discount while it is still available.

Use the code SPECIAL20 at checkout to get the discount. You can find the code in the description below this video.

About Sheets Help

Along with their recent publication of the Google Workspace Add-on Insert Special CharactersΒ for Google Sheets, Sheets Help provides a wide variety of tutorials, tips and tools to help you with your next project.

 

Get the Add-on

Check it out on the Google Workspace Marketplace: Insert Special Characters

Or learn more from the add-on’s homepage.

 

Performance of Google Apps Script Text Finder Class on 2 Approaches to Searching Large Datasets

Inspired by research into a recent blog post, the Google Apps Script Text Finder Class’ Find All (findAll()) and Find Next (findNext()) methods were benchmarked over two different datasets containing 50,000 rows. The first dataset contained 1,000 cells matching the search text. The second dataset contained 100 matching cells.

For each dataset, a test was conducted to retrieve either the first 10 matching cells or the first 100 matching cells. The Find All and Find Next approaches were tested and compared on each test.

It was expected that Find Next would perform best on the condition where the dataset contained a large number of found items and only a small number of first cells needed to be reported. The benchmark results suggest that this hypothesis is most likely.

First number of cells to retrieve Test Function Avg. run time over 100 runs. Fastest Function Fastest Avg. Time Avg. time Difference
1000 items to find
10
1
v2 findAll 1626.24 v3 findNext 1368.45 257.79
v3 findNext 1368.45
50
2
v2 findAll 1578.19 v2 findAll 1578.19 4993.61
v3 findNext 6571.8
100 items to find
10
3
v2 findAll 360.94 v2 findAll 360.94 975.16
v3 findNext 1336.1
50
4
v2 findAll 377.13 v2 findAll 377.13 6175.59
v3 findNext 6552.72

Table: The average time in milliseconds of 100 runs of each test of Apps Script Text Finder findAll() and findNext() methods. Image link for mobile-friendly viewers.

Method

Sample Data

Two columns of data 50,000 rows deep were generated for this test. Each cell in each column consisted of a number; either 1, 2, 3, 4 or 5. An equal spread of numbers 1 through 4 where added to each row. Each column differs by the number of 5s in each row:

  • Col A:Β 1,000 5’s
  • Col B:Β 100 5’s

Each column was then selected and randomised with: Data > Randomise range.

Test

Two functions are compared to test their performance based on four test conditions based on 100 runs of each test:

  1. Retrieve the first 10 cells containing the search text where the range contains 1,000 matching search items.
  2. Retrieve the first 50 cells containing the search text where the range contains 1,000 matching search items.
  3. Retrieve the first 10 cells containing the search text where the range contains 100 matching search items.
  4. Retrieve the first 50 cells containing the search text where the range contains 100 matching search items.

The time in milliseconds was recorded using the JavaScript Date.now() method before and after the functions were run. The difference in time in milliseconds was then appended to an array and added to a Google Sheet column for each test type. This culminated in 8 sets of 100 results.

The average of each test was then recorded and used to compare performance.

Note: Performance.now() is not available in Google Apps Script.Β 

Code

All code and results can be found copied from this sheet:

Analysis of Google Apps Script Create Finder Class Retrieve n found values

To explore the code and run your own independent tests, make a copy of the Google Sheet: File > Make a copy.

More detailed breakdowns of the code for each test function can be found in the source tutorial.

Note! There is no v1. The version numbers refer to the tutorial related to this post.

Main Test RUN

This function ran all the test conditions. Modify colPastePosition to add the culminated times to the desired columns. Then uncomment the desired run.

test_v2 – Google Apps Script Text Finder Class- findAll()

Code breakdown can be found here: link.

This function retrieves the full list of all found cells using the findAll() method from the Text Finder Class. All available found items in the range are then stored in the found variable.

It then relies on a for-loop to iterate through each cell and collect the cell location using the Spreadsheet App Class’ range getA1Notation method. Each cell location is then stored in the locations variable as an array item before returning the array to the initialising function.

The for-loop breaks when the total number of required cell items (the position) equal the index variable (i) in the loop.

test_v3 – Google Apps Script Text Finder Class- findNext()

Code breakdown can be found here: link.

In this function, a call is made to the spreadsheet to retrieve the found cell value each time findNext() method of the Text Finder Class is called. On each iteration, the getA1Notation method is used to retrieve the cell location. This location is then stored as an array value in the locations variable before being returned to the initiating function.

The function used a while-loop to iterate through each next item found until the counter – or the number of required cells to collect – is reached.

Results & Discussion

Analysis of Google Apps Script Create Finder Class Retrieve n found values
Performance in Milliseconds to Retrieve the first 10 or 50 Matching Values over a 50,000 Row Range Contain Either 1000 or 100 Matchable items Using the Google Apps Script Spreadsheet App Finder Class.

Test 1: Retrieve the first 10 cells containing the search text where the range contains 1,000 matching search items.

Version 3 –findNext() performed better on average when there were 1000 potential items to find in the range but only the first 10 items need to be selected. Versions 3’s average speed was 1368.45ms compared to version 2’s average run speed of 1826.24ms. This is a performance increase of 257.79ms for version 3.

Version 2’s lower performance is likely due to needing to collect all available found cells before it can extract the top 10 items.

Version 3, makes 10 calls to the Google Sheets in this example. Compared to version 2, this takes relatively less time than collecting all available found cell references to the search item.

TEST 1: 1,000 randomised items to find in 50,000. Return first 10 matches using v2-findAll and v3-findNext functions.
TEST 1: 1,000 randomised items to find in 50,000. Return first 10 matches using v2-findAll and v3-findNext functions.

Test 2: Retrieve the first 50 cells containing the search text where the range contains 1,000 matching search items.

Version 2 – findAll() performed significantly better over 100 runs than version 3 when retrieving the top 50 found cells from a possible 1000. Version 2 was, on average, 4993.61ms faster at an average runtime of 1578.19ms compared to version 3’s sluggish 6571.80ms average.

It was expected that test one and test two’s times for version 2 would be similar and there are only 48.05ms between their average runtimes.

Version 3’s poor performance is likely due to its reliance on calling the spreadsheet to collect the cell data on all 50 calls it needs to make.

TEST 2: 1,000 randomised items to find in 50,000. Return first 50 matches using v2-findAll and v3-findNext functions.
TEST 2: 1,000 randomised items to find in 50,000. Return first 50 matches using v2-findAll and v3-findNext functions.

Test 3: Retrieve the first 10 cells containing the search text where the range contains 100 matching search items.

Version 2, again, performed better by 975.16ms than version 3 when there was a smaller potential number of items to find in the range and only the first ten items need to be retrieved.

Here the performance margin between the two versions was closer than in the previous test. Version 2’s average run speed was 360.94ms while version 3’s runtime was 1336.10ms.

With a smaller number of retrieved items, the version 2 findAll() function did not have to work as hard to collect the methods related to each range it collects. Whereas version 3 still needed to make 10 performance-intensive calls back to the Google Sheet each time with relatively no performance change to test one.

TEST 3: 100 randomised items to find in 50,000. Return first 10 matches using v2-findAll and v3-findNext functions.
TEST 3: 100 randomised items to find in 50,000. Return first 10 matches using v2-findAll and v3-findNext functions.

Test 4: Retrieve the first 50 cells containing the search text where the range contains 100 matching search items.

Predictably, version 2 – findAll() performed the best when the expected match sample is small (100 available matches) and the total first set of cells to retrieve was relatively large (50).

Version 2’s average completion time was 377.13ms compared to version 3’s average of 6552.72ms, performing on average 6175.59ms faster. This is by far the largest margin on performance between the two versions.

Here again, version 3 must perform 50 calls to the Google Sheet, each one retrieving the cell range data. Alternatively, version 2 makes one call to the spreadsheet and then retrieves the cell data for all collected values. This is significantly faster than version 3’s approach.

TEST 4: 100 randomised items to find in 50,000. Return first 50 matches using v2-findAll and v3-findNext functions.
TEST 4: 100 randomised items to find in 50,000. Return first 50 matches using v2-findAll and v3-findNext functions.

Overall

On datasets that may have the potential to contain a large number of matching items, but fewer required results to return, version 3 may be the best option. In all other cases, version 2 is the most optimal approach to finding data in a range.

It is important to note that it can be difficult to accurately measure performance with Apps Script runs because resource allocation to run a script does seem to vary. Nevertheless, with a sample size of 100 runs, it is hoped that average values will be more accurate than a smaller sample.

Grab Your Own Copy of the Google Sheet and Attached Code here

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

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

 

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.

~Yagi

 

Find first, last & nth value in a Google Sheets range with Apps Script

In this tutorial, we will explore how to find the first and last values in a Google Sheets Range using Google Apps Script. Then we will modify our code to find a value at a specific location. We will then find the position of the first set of values in our Google Sheets range. Lastly, we will create a reusable function to find the first or last set of values in a range.

This tutorial accompanies the YouTube tutorial of the same name:

The starter sheet for the video tutorial:

Starter Sheet

The code for each section of the tutorial can be found below under each section header along with any explanation, where needed.

In our previous tutorial, we covered how to find all values in a Google Sheet, a sheet table or a range. Check it out here:

Find All Values in Google Sheets with Apps Script


The Runsies Function

This is an example function that you can use to run your find functions below. All arguments for the functions below are placed in here along with the execution of the desired function.

In the example below we are running the first function.

 

Find the first value or text in a Google Sheets Range using Apps Scripts FindAll method

In this approach, we make use of our previous tutorial’s script and use the findAll method of the createTextFinder Class.

This method returns an array for each found item that can access the Google Apps Script range class methods.

Line 15 – Once all items in the range are found, we can select the zeroeth item. Incidentally, we could get the last item in the range with this approach by modifying this line to:

const lastVal = foundValue[foundValue.length - 1];

Of course, you would need to update the variable names too.

Line 17 – Here we log the cell position of the first found item using the SpreadsheetApp Range Class getA1Notation method.

Line 19 –Β Finally to make it easier to test. We set our selected cell value to activate. This makes the cell active and makes it easy for us to crosscheck in our testing. It also has the benefit of navigating the user on the Google Sheet to the desired cell. Check out the image below for an example:

Find first value in a Google Sheets Range with apps script and activate it

Note! This approach can be much, much slower than the next option, particularly if your text finder discovers a lot of cells.

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

Find the first value or text in a Google Sheets Range using the iterator method

A much more common approach to finding the first position of the matching value is using the findNext() iterator method of the Text Finder Class.

This is considerably faster on large datasets where you expect to find many occurrences of the found item. Why? Because, the find-all approach will collect all cells containing the value, whereas findNext() will only collect the next value to be found.

Line 13 –Β Here we replace findAll() with findNext().

Find the last value or text in Google Sheets Range

In this example, we swap the findNext() method with the findPrevious() method.

Interestingly, if we call the find previous method straight after creating the text finder, It will look for the first item starting in reverse order. This means it will start its search from the bottom of the range.

 

Find the position of the nth value in a Google Sheets Range with Apps Script

Here we want to find theΒ nth value in a range. Perhaps the 3rd value or the 10th.

Lines 14-15-Β  In this function, we return the findAll() method and then identify the position of the value in the selectedVal array.

Line 12 –Β Note that we will need to subtract one from our position value here before we can use it to find the value in the array. Remember, the array will start at zero.

 

Find the first n values in a Google Sheets Range

In this scenario, we want to find a starting set of values from our range. Maybe we want to grab the top 3 found cells or the first 5.

Line 15 – Here we use the findAll() method again to get a list of all values in the range.

Line 19-29 – Next, we will use a JavaScript ‘for’ loop to iterate over the found cells. We will need to store all the found A1 notation locations in a locations variable on line 19.

LineΒ  25 – On each iteration, we will append the locations with our new cell value.

Line 28 –Β However, if the index (i) matches the same number as the position variable then we want to break our loop.

 

Find the first or last values of a selected number in a Google Sheets Range

Finally, we have two functions here. Both functions allow you to find either the first set or last set or cells where the search term is found. Their usage really depends upon the type of data that you are working with.

Both functions take 4 arguments:

  1. sheetName – The name of the sheet tab.
  2. text – The text to search.
  3. n – The number of found cells to collect.
  4. reverse (optional) – If true, conduct the search in reverse.

Again, both functions will return an array containing all found cell locations in A1-notation.

Checkout the post below for a detailed benchmark analysis of each function:

Performance of Google Apps Script Text Finder Class on 2 Approaches to Searching Large Datasets

 

Find All Approach

This approach is more performant when you don’t expect to find a lot of matching cells in a large range. It is also suitable if you want to extract a larger list ofΒ nΒ items starting from the beginning or end of the range.

Why? Because if there are a large number of found variables then the findAll method will take more time to collect the full list of ALL cell locations before we can continue and select the ones we want. Whereas if we use the next option using findNext or findPrevious then each item will be retrieved one at a time, making the second option more performant.

Alternatively, if we want to retrieve say the first 100 items, then the first item would be a better approach. This is because we only make one call to the Google Sheet instead of 100 which is a much slower approach.

Line 16 – Here, we use the findAll() method again.

Line 22 – Note the if-statement here that checks if the reverse parameter is set to true.

Line 24 – If we want to start the search from the bottom of the range, we first set a counter to zero.

Line 25 – Then we run a reverse for loop, starting from the bottom of the found array.

Line 29 –Β If we find a cell we add it to the locations list like in our previous example.

Lines 31-33 – Finally, we update the counter and then check the counter count againstΒ n and break the look if we have a match.

Lines 36 -46 –Β If there is not reverse argument or the argument is set to false then we want to start our search from the top of the range. Here, we use the same for-loop as the previous chapter.

 

Find Next or Previous Approach

This approach performs better in a large range when there the range contains many found cells, but you may only need to collect only a few of the first or last proceeding items.

Line 15 –Β To start our search, we only initialise the text finder class.

Line 17 – Set our empty location array.

Line 18 – Creates a counter base on the number (n) of found cell locations that we want to retrieve.

Line 20 –Β Next, we generate JavaScript while loop to finish once the counter reaches 1. The loop will either find the next or find the previous cell range.

Line 22 –Β We set the found variable to receive the cell location.

Lines 24-28 – If we have set the item to be reversed we use the findPrevious method and collect each cell location.

Lines 29-34 –Β Alternatively, we will use the findNext method if reverse is set to false or not included.

Line 36 –Β Next, we push the cell reference to the locations array.

Line 28 –Β The last task in the loop is to decrease our counter by one.

Line 43 –Β Outside our loop, we return the locations array back to the initiating function.

 

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

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

 

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.

%d bloggers like this: