On a recent board post, a Google Sheets user wanted to change a four-digit number (for example, 1230) to a time, like 12:30, in the same cell that the item was entered.
Unfortunately, the user was not in a position to change the starting values, so they were left with the 4 digits.
There are two ways of doing this with varying levels of complexity:
Sometimes your Google Sheet tabs can get out of hand. They can be mixed up and confusing to users. It’s often necessary to simply sort them in ascending or descending order.
In this tutorial, we will use Google Apps Script to sort tabs in Google Sheets. We’ll also use a handy menu bar to quickly run the sort.
The approach below relies on a natural sort. In a normal sort where you also have numbers say:
"2. Cheese", "10. Pizza", "1. Bananas"
Then you ran your sort, you would not get what your expected but rather:
"1. Bananas", "10. Pizza", "2. Cheese"
With a natural sort, we consider the number numerically, rather than as characters. This means our sort would come out as expected:
"1. Bananas", "2. Cheese", "10. Pizza"
You can learn more about creating the Apps Script by following the video below or you can jump down and grab a copy of your code and run it in your own project.
// Iterates through each sheet sets it to activve and updates it order.
sheetNames.forEach((sheet,idx)=>{
ss.setActiveSheet(sheet)
ss.moveActiveSheet(idx+1)// Sheet tab indexes start from one so we must add one.
});
}
};
Looking to learn more about Google Apps Scripts in a more structured format? Udemyhas 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.
Code Breakdown
onOpen()
onOpen
1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* Creates a menu item for ascending and descending sheet tab sort.
Line 8: To create a menu we use the Create Menu method and add the menu label “Extras” as an argument.
Lines 9-10: Next, we can add menus to the main menu header with the Add Item method. These menus take a menu label and then a function or an object method that will run when the menu is selected. Ensure that you don’t include parentheses in these arguments and contain them in a string.
Line 11: Finally, we need to build the menu by adding all the menu items to the UI.
You can learn more about building menus in Google Sheets, Docs and Slides here:
The sortTabs property does all the heavy lifting in this object.
It takes a boolean as an argument that will determine if the sort is ascending or descending.
Get a list of sheets
Get a list of sheets
1
2
3
constss=SpreadsheetApp.getActiveSpreadsheet();
constsheets=ss.getSheets();ss.sheet
Our first task is to get an array containing all the Google Sheets in the currently active sheet. We can do this with the SpreadSheet App Get Sheets method. This will contain an array with all the methods available for each found sheet tab.
Using Intl Collator for natural sorting
We want to sort our sheet tabs naturally just in case we have numbers in the name of the tab (e.g. “1”, “2”, “4. Cake”). We can do this with the JavaScript Intl.Collator object to sort the sheet tabs in a natural order, meaning that numeric values are sorted in numerical order and text values are sorted alphabetically. You can modify this function to use a different sorting algorithm or change the sorting order.
new Intl.Collator JS
1
2
3
4
constcollator=newIntl.Collator(undefined,{
numeric:true,// Sets numeric collation so 1 < 2 < 10
sensitivity:'base'// Ignores accents and other diacritic marks in lettering.
});
Line 2: Here, we create a new Intl.Collator constructor. The first optional parameter of the constructor defines the locale or language tab. We don’t need this option, so we set it to ‘undefined’.
The second parameter sets the options for the collator.
Line 3: First, we use the numeric property and set it to true. This will allow us to order the numbers properly so that 1 < 2 <10.
Line 4: Secondly, we set the sensitivity to base. This means that we do not take into account any accents or other markings on letter characters. If you are using this Google Sheets sort tab code in other languages, then you might want to modify this.
Sort Google Sheet tabs Apps Script-side
Now that we have our collator set up we use the JavaScript sort method to sort through the array of sheet names.
Sort apps script-side
1
2
3
4
5
// Sorts the sheet.
let sheetNames=sheets.sort((a,b)=>{
// Compares first sorted sheet name value against last sorted sheet name value.
returncollator.compare(a.getName(),b.getName())
})
Line 2: Here, we use an arrow function with a standard a, b parameter set. These parameters refer to the first and second elements of comparison respectively.
Line 3: Use our collator and apply the compare method to compare the sheet names against each other.
Reversing the sort
Reversing a sort
1
2
// If set to descending the sheetNames lists is ignored.
Line 3: Inside each loop, we need to set the active sheet to the currently iterated sheet.
Line 4: Finally, we move the active sheet to the next position in the sheet tabs. Note that sheet indexes start from one (1) however our array index starts from zero (0). This is why we need to add one to the index.
That’s all there is to it.
If you want to learn more about how to modify Google sheets tabs with Apps Script, check out these tutorials:
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.
Table of Contents
V1 – Basic Find and Hide Rows based on cell values in Google Sheets
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:
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:
// If the the current row is the same as the previous. Skip this row.
return;
}elseif(lastRowRangeRow===row){
// If the next row number is equal to the sum of the start row and number of rows to count.
++rowRange.numRows;
// If this is the last row in the range
if(idx===allOccurrences.length-1){
hideRange(rowRange);
};
}else{
// If the new row is not part of the previous range.
hideRange(rowRange);
rowRange.startRow=row;
rowRange.numRows=1;
// If this is the last row in the range
if(idx===allOccurrences.length-1){
hideRange(rowRange);
};
}
})
SpreadsheetApp.flush();
};
In larger, ranges we might have a lot of situations where our found text is on multiple adjacent rows.
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:
Line 63 – Run the hideRange on the current rowRange variable set.
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.
Looking to learn more about Google Apps Scripts in a more structured format? Udemyhas 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.
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.
hideAllRowsWithVal_v3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* Hide or unhide all rows that contains the selected value.
* Single sheet
* Uses Google Sheets Advanced Service Batch Update.
* @param {string} text - the text to find.
* @param {string} sheetName - the target sheet.
* @param {boolean} [isHide] - True to hide false to show.
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:
Update Dimension Properties
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
'updateDimensionProperties':{
"range":{
"sheetId":sheetId,
"dimension":'ROWS',
"startIndex":setRange.startRow-1,
"endIndex":setRange.endRow,
},
"properties":{
"hiddenByUser":isHide,
},
"fields":'hiddenByUser',
}
}
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.
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 and activate the first or last row in a Google Sheet with Apps Script
Selects the row that contains the first found value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Selects the row that contains the first found value.
* Single sheet
* @param {string} text - the text to find.
* @param {string} sheetName - the target sheet.
*/
functionselectFirstRowWithVal(text,sheetName){
console.log(text,sheetName)
constss=SpreadsheetApp.getActiveSpreadsheet();
constsheet=ss.getSheetByName(sheetName);
consttextFinder=sheet.createTextFinder(text);
constcell=textFinder.findNext();
// const cell = textFinder.findPrevious();
constrow=cell.getRow();
sheet
.getRange(`A${row}:${row}`)
.activate();
};
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 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:
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
Select all rows that contains the selected value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Select all rows that contains the selected value.
* Single sheet
* @param {string} text - the text to find.
* @param {string} sheetName - the target sheet.
*/
functionselectAllRowsWithVal(text,sheetName){
constss=SpreadsheetApp.getActiveSpreadsheet();
constsheet=ss.getSheetByName(sheetName);
consttextFinder=sheet.createTextFinder(text);
constallOccurrences=textFinder.findAll();
constranges=allOccurrences
.map(item=>`A${item.getRow()}:${item.getRow()}`);
sheet.getRangeList(ranges).activate();
};
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.
Finds and activates all rows in the range that contain ‘Koala’.
Find and format all rows in a Google Sheet with Apps Script
Format all rows that contains the selected value.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Format all rows that contains the selected value.
* Single sheet
* @param {string} text - the text to find.
* @param {string} sheetName - the target sheet.
*/
functionformatAllRowsWithVal(text,sheetName){
constss=SpreadsheetApp.getActiveSpreadsheet();
constsheet=ss.getSheetByName(sheetName);
consttextFinder=sheet.createTextFinder(text);
constallOccurrences=textFinder.findAll();
constranges=allOccurrences
.map(item=>`A${item.getRow()}:${item.getRow()}`);
sheet.getRangeList(ranges)
.setBackground('#0b5394')
.setFontColor('white')
.setFontWeight('bold')
};
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.
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:
Clear Format – clearFormat() – Clears the formatting of the selected range.
Set background Colour – setBackgroundColor(colour) – Use CSS notation like hexadecimal colours, colour names or RGB colours
Set font Colour – setFontColor(colour)– Use CSS notation like hexadecimal colours, colour names or RGB colours.
Set font Weight– setFontWeight(type) – Either “bold” or “normal”.
Set font Size= setFontSize(size) – The font size as a number.
Set font Style – setFontStyle(style) – The style, e.g. “Helvetica”, “Poppins”.
Set text rotation – setTextRotation() – 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.
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:
Retrieve the first 10 cells containing the search text where the range contains 1,000 matching search items.
Retrieve the first 50 cells containing the search text where the range contains 1,000 matching search items.
Retrieve the first 10 cells containing the search text where the range contains 100 matching search items.
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:
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.
Apps Script Text Finder Find All
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* Finds the first set of matching cells of n in length or less.
* @param {string} sheetName - the name of the sheet tab.
* @param {string|number} text - text to search.
* @param {number} n - the max number of items to report.
* @param {string} rangeLoc - A1- Notation of selected range.
* @return {array} - Array of cell positions of the found match.
*/
functiontest_v2(sheetName,text,n,rangeLoc){
constposition=n-1;
constss=SpreadsheetApp.getActiveSpreadsheet();
constsheet=ss.getSheetByName(sheetName);
constrange=sheet.getRange(rangeLoc)
constfound=range.createTextFinder(text)
.findAll();
let locations=[];
for(leti=0;i<found.length;i++){
constcell=found[i];
locations.push(cell.getA1Notation())
if(i===position)break;
}
returnlocations;
}
test_v3 – Google Apps Script Text Finder Class- findNext()
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.
Apps Script Text Finder Find Next
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Finds the first set of matching cells of n in length or less.
* @param {string} sheetName - the name of the sheet tab.
* @param {string|number} text - text to search.
* @param {number} n - the max number of items to report.
* @param {string} rangeLoc - A1- Notation of selected range.
* @return {array} - Array of cell positions of the found match.
*/
functiontest_v3(sheetName,text,n,rangeLoc){
constss=SpreadsheetApp.getActiveSpreadsheet();
constsheet=ss.getSheetByName(sheetName);
constrange=sheet.getRange(rangeLoc)
constfinder=range.createTextFinder(text)
let locations=[];
let counter=n;
while(counter>0){
let found="";
found=finder
.findNext()
.getA1Notation();
locations.push(found);
--counter;
};
returnlocations
};
Results & Discussion
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 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 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 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.
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.
Looking to learn more about Google Apps Scripts in a more structured format? Udemyhas 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.