Google Apps Script – Copy and Paste Cells While Retaining Column Width in Google Sheets.

Google Apps Script

Have you ever copied and pasted something in Google Sheets only to be frustrated with the fact that it stubbornly refuses to paste the column widths? I mean, everything else is perfect, the formatting, the formulas the comments, they all were pasted across just fine. However, that dastardly column width just does not budge.

copied Google Sheet
When you want to copy and paste this…
Paste without column widths.
…but you get this.

Continue reading “Google Apps Script – Copy and Paste Cells While Retaining Column Width in Google Sheets.”

Google Apps Script – Disable Enable Submit Button in Sidebar

Google Apps Script, Javascript, Jquery, HTML

I was working on a Google Apps Script project lately in Google Sheets that set up parameters in a sidebar and then ran the process once the user clicked the “Submit” button. The problem was that the process was taking a while and that “Submit” Button was ripe to be clicked multiple times by the impatient user, before the server-side code could even finish it’s operation.

To fix this I needed to disable the submit button once it had been clicked and then enable it again once the server-side process was complete. Here, I need to:

  1. Disable the button and get the data from the client-side Javascript inside my sidebar’s html file.
  2. Do something awesome with it server-side.
  3. Upon the completion of the server-side awesome, call back to the html file and enable the button again.

The Example

I have a very simple Google Sheets Side Bar with a “Submit” and “Cancel” button. When the “Submit” button is clicked it calls the function submittington (can he get any more creative? No. No he can’t).

This function then disables the “Submit” button sends a variable to the client side code.gs and displays it stylishly in the sheet multiple times for the users viewing pleasure. After the code.gs function is executed, it calls back to the client-side submittington function and enables the button.

Behold!!! The example:

Disable Enable Button in Sidebar Google Apps Script

Continue reading “Google Apps Script – Disable Enable Submit Button in Sidebar”

Google Apps Script – How to create Javascript and CSS files for a Sidebar Project in Google Apps Script

Google Apps Script-templates, Javascript, CSS

So, I started working on a larger Google Sheet Sidebar project in Google Apps Script recently and I quickly realised that it was going to be a mess if I didn’t separate my Javascript, CSS and even some of my HTML into separate files. However, if you have ever noticed in the script editor that there is no way for you to add script or style files to the code. Your only two options are Google Script files *.gs and Html files *.html.

Project File Types - Google Apps Script

Then, what’s the trick?

The trick is to create separate html files for your CSS and Javascript and include or import them into your main html file. Unfortunately, you can’t do this with the standard:

HtmlService.createHtmlOutputFromFile(filename)

Instead, we will need to use the templating method:

html = HtmlService.createTemplateFromFile(filename)

We will  get into a little more detail on templates later in this tutorial.

My main reference for this was the Google Apps Script UI best practice guide, and you will see code snippets of the first example there that I have modified for my own example.

The thing is, the explanations were a bit vague for me to work out clearly so I really needed to create an example of my own to work through how to use it. The example below breaks down the steps to create file relationships to make your code look neater. It also dives into some uses of template statements in html.

The Final Result

The goal of our little sidebar project will be to display a sidebar with colored paragraph text, a list generated with Javascript and a randomly assigned body page the contain the text “Body 1” or “Body 2”.

Take a look at the demo:

Sidebar Example - Google Apps Script

Continue reading “Google Apps Script – How to create Javascript and CSS files for a Sidebar Project in Google Apps Script”

Google Apps Script – How to Alternate Colors in an Ordered List by Column Category. 

Google Apps Script and Google Sheets

Imagine that you have a Google Sheet that you have sorted by a certain column. You might be sorting by the surname of your sales team, class sections or regions. To make the sheet easier to read for your team, you want to alternate the background colors after each category in your sort column is complete.

The Example

I have the following list of numbers in column 1 and 2. I have sorted these numbers by my Grouping Column of planets in column 3. After each grouping, I have alternated the background color to make the transition easier to read.

Alternating color by section - Google Apps Script

The Code

Continue reading “Google Apps Script – How to Alternate Colors in an Ordered List by Column Category. “

Google Apps Script – Get the Start Row and Length of Each Category in an Ordered Column in Google Sheets

Google Apps Script and Google Sheets

Quite often I will need to get the range of each category in an item and do something with it in Google Sheets. For example, I work in education, I will often have rows of students that are categorized by class sections. I will then be asked to do something like those sections like put each section of students in their own sheet or set alternating colors for each section to make the sheet easier to read.

Alternatively, you may want to grab sales data by region or sales items by a particular category and work with them in Google Apps Script.

The Example

Let’s say we want to get the range values of the follow sheet by planets. We will be categorizing our data by the Grouping, column C.

Grouping By Planet - Google Apps Script

First we don’t want to take into account the headers on the first row. Our first grouping will be Mars, followed by Jupiter, Uranus and Mercury. We want to know which column that each category starts on and how many of that category there are.

The Code

Continue reading “Google Apps Script – Get the Start Row and Length of Each Category in an Ordered Column in Google Sheets”

Set the Paper Size and Orientation in a Doc Using Google Apps Script

Sometimes you need to prepare a Google Doc’s paper size and orientation programatically using Google Apps Script.

Unfortunately, you can’t just call for say, A4 in Landscape. Okay, not until now (see my code below).

Google Apps Script does provide a way to set the dimensions of your page  in the body class by using:

  • setPageWidth(pageWidth)
  • setPageHeight(pageHeight)

The page widths and heights are measured in PostScripts Points which is a bit of a pain too.

Here is an example of setting and A3 paper size in Landscape.

Ugh. What a chore. You need to find the dimensions of the paper in points.

Enter this little nifty function and your life will be so much easier:

Continue reading “Set the Paper Size and Orientation in a Doc Using Google Apps Script”

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

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”

How to Get Something from Google Sheets and Display it in the Sidebar in Google Apps Script

What if you want to get a value or a range from Google Sheets and show it in your sidebar using Google Apps Script?

First you will need to get the value or range by using Googles server-side script. Then you will have to display it client-side in your HTML document.

Documentation on getting the server-side and client-side talking nicely to each other is a little vague. Hopefully, this very basic tutorial will help clear things up.

In this tutorial I will also be using Jquery.

Let’s get started.

Continue reading “How to Get Something from Google Sheets and Display it in the Sidebar in Google Apps Script”

Google Apps Script – Iterating Through Ranges in Sheets the Right and Wrong Way

I was trying to rush out some Google Apps Script code to deal with a task on Google Sheets recently. Basically, I had to search through a heap of data and find certain values and do something too them.

My column was reaching across the page to something like Column BK and my rows were over 1000 deep. Running this code was taking forever!!!

My immediate instinct was:

What have I done wrong?

…and my instinct was right.

The Good and Bad Way to Search Through Code

So after looking at my code again, I discovered that for some reason I go it into my head that I should be searching each cell for the value I needed and then doing something with it.

Sounds logical right? It’s sorta what you are meant to do.

The problem is that I was calling the sever and asking for the range in each cell as I was looping through the entire document. This is super costly and inefficient in terms of time.

Google talks about this in their Google Apps Script Best Practice page under Batch Operations.

Also, if you do run a costly code like this, then you will get a little red light in your Script tool bar that represents your Execution Hints:

Google Apps Script Execution Hints

Clicking on Execution Hints and expanding the side bar with provide you with a far-too-deserving-polite dressing down about your slow and server costly code.

Method Range.getValue is heavily used

The Good

So instead of calling the server for each cell I need to get the full range of the data I am working on, search through it client-side to find what cells require modifying and then invoke the modifications.

Let’s look at a simple example:

Example

In this example I want to search through all the results over multiple quizzes and if there is a dash “-” or a zero “0” change the background accordingly.

Yeah! Yeah! I can do this with conditional formatting, but this is an example, damn it, Jim!!!

Below is a sample of the data I will use and here is the link.

Both Good and Bad examples have the same end result. The result should look like below:

First let’s set up the Google Apps Script code file by calling the user interface, sheet and range of data. (Lost? Create your first Apps Script)

Hopefully everything is self-explanatory here. We call the spreadsheet first and then look for the active sheet. Inside the active sheet we want the range of the data (rangeData) which will contain all the data in the range. We will use that data to get the last row and column number of the data. Finally we will call the server to get he range we want to work with (searchRange).

Once done, we will create our function, onOpen(). When it is called it will create a menu called Checker with the sub menu Bad Way and Good Way. This isn’t necessary, but it might be easier for you to physically test the difference in the slow method versus the fast (correct) one.

The Bad Way

As mentioned above in the Bad (slow) Way we call the server each time to look at what is in a cell.

As I loop across the columns and then the rows, I am using my search range to get the value of the cell in Line 25. This means I am contacting the server a total for 436 times. This significantly slows things down.

The Good Way

 

In the preferred approach I am taking the array that I created from searchRange.getValues() in Line 36  and searching through it before I make my calls to change the background when a dash or a zero occurs.

Why is this better?

I only make server call to collect the range data once. Then client-side (on my computer in this instance), I do all my searching before calling Google who collects all the changes in a cache until the loops are done before creating background colors all at once.

Super fast.

Speed comparison. 

Take a look at the speed differences over ten tests:

The Good Way is the clear winner. You can try it out for yourself if you have been playing along by going to <View><Execution Transcript> in the Script

Take Home

The take home from this is that, make as little calls to the server as possible. It significantly improves your speed.

The Full Code

 

 

 

 

 

 

Spacer – Free Google Add-On That Spaces Row by Column Category

What is Spacer?

Spacer is a Free Google Add-On that creates row spaces by column categories.

I use it as an academic administrator to create a space or two at the end of each class section to create a visual break between sections. This makes it easier for my staff to quickly identify class sections.

You can find Spacer at the Google Chrome Webstore.

Chrome Web Store Badge

What can Spacer do?

Spacer can:

  • Automatically detect the width of your columns.
  • Allow you to select a column with the categories you want to use to space your data.
  • Set the height of your header – so that is not spaced too.
  • Set the thickness of your spaces.
  • Set the color of your spaces
  • Set starting and end position of your color filler.

How to use Spacer

After Installation

Before You Start:

  1. Before you start, create a Google Sheet with the data in it you want to space.
  2. Select All the data.
  3. Go to the menu bar and select: Data>Sort Range...   and select the column you want to sort by. This will be the column you will use to space your data by the categories in that column.
Running Spacer:
  1. In a Google Sheet, select the Add-Ons menu.
    Google Sheets Add Addon
  2. Select: Spacer>Create SpacesOpen Spacer for Google Sheets
  3. sidebar will appear to the right.
    spacer sidebar for Google Sheets
  4. Choose the column you want to use to Space your data.
  5. Choose how high your header is.
  6. Chose how thick or deep your want your header to be.
  7. If you want a color, select a color that you want to add to your spaces.
  8. Select where you want to start the color and end the color.
  9. Click: Submit
  10. If you are not happy with the color, space, color width or made a mistake, simply click: UNDO
Troubleshooting

I keep getting the following popup:

troubleshooting Spacer

This is because the starting value of your Color Width is greater than your End value:

Spacer RightSpacer Wrong

An Example

I have a list of people with their favorite color and fruit. Let’s say I want to sort the Google Sheet by favorite color (Fav Color) and put a space at the end of each color category to make it easier to read.

My data looks like this:

Favorite Data Example

To space this data we must do the following:

  1. Select all the data: ctrl+shift + a
    Select Data
  2. Sort the data by column B. Select: Data> Sort range
    sort data select range
  3. Click the: Data has a header row  tick box. Select the column: Fav Color. Then click the Sort button.
    Sort Range by column
  4. Your data is now sorted by favorite color:
    sorted by fav color
  5. Time to use the Spacer. Select: Add-ons > Spacer > Create spaces
    execute spacer
  6. Spacer will open at Sidebar on the right:
    spacer sidebar for Google Sheets
  7. We want to space our data by Fav Color which is column B. For Column, select: B
    Spacer Select Column
  8. We have a single Row Header so we can leave the header selection at 1:  Spacer header height
  9. We want to give our spaces a thickness of 2 rows:
    Spacer Thickness
  10. Next, we choose a color. Let’s choose purple. A color picker will pop up (the picker may vary depending on your system) select the color and click: OK:                             Spacer color
  11. This is the result:
    Spacer color result
  12. Now choose where to start and finish the color fill for the space. I’ll start it at column A and end it at column E.
    Spacer start and finish color
  13. Finally click Submit:
  14. This will be the result:
    Spacer result

 

Privacy Policy | Terms of Use