You might want to sort some Google Sheet data based on a condition in your Google Apps Script or simply sort by selected columns and rows after inserting a new row.

If you are always building sample data for tutorials like me, you might also be interested in randomising your data programmatically.

Fortunately, Google Apps Script’s SpreadsheetApp Class has built-in methods to handle just that for you. Plus it’s super easy to implement.

Check out the video tutorial below or grab one of the code snippets to add into your own project.

I’ve also partnered with my WebHost GreenGeeks to get 80% OFF the regular price for their three main plans.

Whether you want to whip up your very own WordPress site or build your own site from scratch I can’t recommend GreenGeeks more. I have been with them for over 5 years now and love their top support and ease of use.

Plus their environmental commitment to green energy and tree planting is a win for me.

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:

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

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.

insertRowAtTop_v1

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

/**

* Add a Row of Data Below the Header with Apps Script

* [This is an example]{@link https://yagisanatode.com}

* @author Scott (Yagi) <yagisanatode@gmail.com>

* @license Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)

*/

/**

* Inserts a row at the top below the header.

* @param {array<string>} data - 2d array [[id, date, email]]

* @param {string} sheetName - the name of the selected sheet.

* @param {number} targetRow - the row to insert the data in.

The insertRowAtTop_v1() function takes 3 arguments:

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:

A 2d array from a Google Sheet

1

2

3

4

5

[

["1A","1B","1C"],

["2A","2B","2C"],

["3A","3B","3C"]

]

sheetName – This is the sheet tab name.

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.

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 2. Line 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:

Row Start – This will be the target row we set.

Column Start – All our data will begin in Column A so we set this to one.

Row Depth – We are only inserting one row of data so our depth will be one.

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() method. Line 24

Flush the Spreadsheet

While 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.

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

Here we set our target row to row 2and 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.

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

insertRowAtTop_v2

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

/**

* Inserts a row at the top below the header.

* @param {array<string>} data - 2d array [[id, date, email]]

* @param {string} sheetName - the name of the selected sheet.

* @param {number} targetRow - the row to insert the data in.

* @param {string} namedRangeName - the name of the affected Named Range

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:

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

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() method. Line 22

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

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.

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).

Named Range Set Range

1

2

.setRange(

sheet.getRange(targetRow,1,rowDepth,colWidth)

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.

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

insertRowAtTop_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

/**

* Inserts a row at the top below the header.

* @param {array<string>} data - 2d array [[id, date, email]]

* @param {string} sheetName - the name of the selected sheet.

* @param {number} targetRow - the row to insert the data in.

* @param {string} namedRangeName - the name of the affected Named Range

* @param {boolean} hasFormulas - true if formula columns must be duplicated.

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? 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.

I need to create a lot of sample data for tutorials and courses. One of the things that I needed for a recent course I am building was to generate a column containing dummy passwords in Google Sheets. Each password needed to consist of letters, numbers and characters.

Until recently, this task would have been relegated to Google Apps Script.

However, with the recent introduction of the LAMBDA function (Well, at the time of writing this anyway), we can do so much more with our Google Sheets.

Before we dive into the formula, it’s important to understand that these ‘passwords’ or random strings of characters are dynamically generated. This means every time you update a cell or reload your Google Sheet the characters in each cell will change.

So once you generate your passwords, copy the range and paste the values back in (Ctrl + c, Ctrl + Shift + v). This way only the values remain.

If you just want to grab the formula and be on your way, you can copy it from the section below. However, if you want to learn how it all works, read on for a breakdown.

Table of Contents

The Password Maker Formula

Note in the formulas below there are three parameters that you can change:

[NumChars]: The number of characters in each string in each cell.

[NumRows]: The number of rows to produce the random string of characters in.

[NumCols]: The number of columns to produce the random string of characters in.

Replace the items in the square [] braces with your own values.

For example, if we wanted to generate a matrix of passwords 4 rows deep, 5 columns wide and with each cell containing 12 random characters we would do this:

To quickly change the formula to produce only a certain subset of characters, you will need to delete the desired characters from the string contained in the MID function on line 14 of the example above.

You will also need to change the second argument of the RANDBETWEEN function to the length of your new string of characters.

Hint! You can quickly count the string of characters by copying the characters in the formula (including the double quotation marks on each end) and pasting it inside a LEN function. For example:

=LEN("GOAT!1234") = 9

Check out the sample sets below and their letter lengths for convenience.

In this section, we will walk through the process of creating the random string generator. Not only does this help to provide an understanding of how the formula works, but it also gives you some insight into a good workflow for building your own complex formulas in Google Sheets.

The Video

The Starter Sheet - To Play Along

If you want to get hands-on to make things more fun, grab the starter sheet from here:

This function takes two arguments, the starting value and the end value. Let’s input our range:

=RANDBETWEEN(1,91) = A random number between 1 and 91

It will dynamically return a random value between 1 and 91.

Note! The Google Sheets RANDBETWEEN function updates dynamically. This means that every time you apply a change to your sheet the random number will change.

MID

We can then use the MID function to find a character in the string at a designated position. For us, this position will be determined by the number that our RANDBETWEEN function returns.

MID takes 3 variables:

The reference string or cell.

The start index in the cell that contains the string.

The length of characters to extract.

So in our example, our formulas would look like this:

=MID(B1, RANDBETWEEN(1,91),1) = A random character from our string.

Where B1 in our example is the string of characters.

You can see in the example above that the formula randomly selected the pipe (|) characters from the string in B1.

Set a Sequence of n Columns

Let’s work on another part of the formula now. We need a way to create a string of random characters at any length we desire – we’ll call this n.

The first part of this process is to generate a row that is n cells wide.

This can be achieved with the SEQUENCE function. With this function, we can generate a range or matrix of values at any row or column width.

Number of columns: We will assign our desired n length here.

The Starting value (optional): This will always be 1 in our formula.

The Step between each value (optional): This will also always be one in our formula.

Let’s say we want to create a formula one row deep and five columns across:

=SEQUENCE(1, 5, 1, 1) = Array [1, 2, 3, 4, 5]

Map a Random Character to Each Sequence Item

Now that we have our sequence, we can map a random character to each item in the sequence. To do this we use the Google Sheets MAP function. This is a helper function of the LAMBDA function set.

The MAP function allows you to traverse an array and modify each item in the array. For us, we are going to apply a random character to each item in the sequence we generated.

MAP can take a number of arrays or ranges as its first argument and then a LAMBDA function as its last argument.

The nested LAMBDA array takes an iterator item argument. This represents the current cell the item is modifying as it works through each item in the range. We need to add this argument even if we don’t use it in our formula.

The second LAMBDA argument is the formula expression. That is, what we are doing to change the value in each of the cells.

The delimiter – This is the value we want to use to separate each cell item when we combine it into a string. In our example, we don’t want to separate the characters so we will leave this as an empty string.

The array – This will be the array we generated in the previous section.

In the example above we have created an array two columns wide and five columns deep with a random password length of 5 characters (See the second argument of the SEQUENCE)..

Conclusion

This password generator is a really helpful tool for templating spreadsheets to create examples or quickly generate a password or random string of characters for codes.

As we mentioned above, the passwords will change each time you update the sheet. The best solution to provide a static password would be to use a bit of Google Apps Script Magic connected to an onEdit() function similar to this tutorial:

For whatever reason, sometimes we just need a list of alphanumeric letters and numbers like this “0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ” to run down a column or across a row, or just all packed into one string of text in a cell in our Google Sheet.

I most commonly use an alphanumeric list to index data or use an alphanumeric string in the random assignment of a value.

In this tutorial, we will cover 4 ways to achieve this. Some approaches have different benefits than others. While two of the approaches even use the new Google Sheets LAMDA function.

If you just want to dive in, copy the formula, and get back into your own project, click on the link to the main numbered headers in the table of contents below. You can copy the formula into your project using the copy symbol in the dropdown menu of the formula bar and selecting the formula you want.

Each formula type can be:

Transposed to run across a row.

Join into a string in a cell.

Set to lowercase.

Extended to include a lowercase option.

The How it Works sections are not mandatory reading but might be helpful if you plan to extend the formula or are simply curious.