Blog

Connected Sheets: Analyze Big Data In Google Sheets

The future of Google Sheets is analyzing millions, even billions, of rows of data with regular formulas and pivot tables.

The future of Google Sheets is Connected Sheets.

That’s a bold claim, so let’s explore it.

Check out this formula operating on 1.5 billion rows of data:

Billion Row Formula in Google Sheets

I just ran a COUNT function across 1.5 Billion rows of data. Inside my Google Sheet.

1.5 Billion rows of data!

Whaaaaat?

Fzzzzzzt……that’s the sound of all the circuit boards in my head frying simultaneously ?

Continue reading Connected Sheets: Analyze Big Data In Google Sheets

How to import social media statistics into Google Sheets: The Import Cookbook

Google Sheets has a powerful and versatile set of IMPORT formulas that can import social media statistics.

This article looks at importing social media statistics from popular social media channels into a Google sheet, for social network analysis or social media management. If you manage a lot of different channels then you could use these techniques to set up a master view (dashboard) to display all your metrics in one place.

Contents

  1. Facebook
  2. Twitter
  3. Instagram
  4. Youtube
  5. Pinterest
  6. Alexa rank
  7. Quora
  8. Reddit
  9. Spotify
  10. Soundcloud
  11. GTmetrix
  12. Bitly
  13. Linkedin
  14. Sites that don’t work and why not
  15. Closing thoughts
  16. Resources

How to import social media statistics into Google Sheets with formulas

The formulas below are generally set up to return the number of followers (or page likes) for a given channel, but you could adapt them to return other metrics (such as follows) with a little extra work.

Caveats: these formulas occasionally stop working when the underlying website changes, but I will try to keep this post updated with working versions for the major social media statistics.

Example workbooks: Each example has a link to an associated Google Sheet workbook, so feel free to make your own copy: File > Make a copy....

facebook icon Import Facebook data

November 2018 update: The Facebook formula is working again! The trick is to use the mobile URL 😉 Thanks to reader Mark O. for this discovery.

Start with the mobile Facebook page URL in cell A1, e.g. this url

https://mobile.facebook.com/benlcollinsData

or this variation of it:

https://m.facebook.com/benlcollinsData

Here is the Google Sheets REGEX formula to extract page likes:

=INDEX(REGEXEXTRACT(REGEXEXTRACT(LOWER(INDEX(IMPORTXML(A1,"//@content"),2)),"([0-9km,.]+)(?: likes)"),"([0-9,.]+)([km]?)"),,1) * SWITCH(INDEX(REGEXEXTRACT(REGEXEXTRACT(LOWER(INDEX(IMPORTXML(A1,"//@content"),2)),"([0-9km,.]+)(?: likes)"),"([0-9,.]+)([km]?)"),,2),"k",1000,"m",1000000,1)

The following screenshot shows these formulas:

Facebook Data

See the Facebook Import Sheet.

^ Back to Contents


twitter logo Import Twitter data

This formula is no longer working for extracting Twitter followers and I have not found an alternative.

Start with the mobile Twitter handle URL in cell A1, e.g.

https://mobile.twitter.com/benlcollins

Here is the formula to extract follower count:

=VALUE(REGEXEXTRACT(IMPORTXML(A1,"/"),"(?:Following )([\d,]+)(?: Followers)"))

The following screenshot shows this formula:

Import twitter data

Note 1: This Twitter formula seems to be particularly volatile, working fine one minute, then not at all the next. I have two Sheets open where it’ll work in one, but not the other!

See the Twitter Import Sheet.

^ Back to Contents


Build Business Dashboards With Google Sheets

Digital marketing dashboard in Google Sheets
  • Learn how to build beautiful, interactive dashboards in my online course.
  • 9+ hours of video content, lifetime access and copies of all the finished dashboard templates.
  • Learn more

instagram logo Import Instagram data

This formula is no longer working for extracting Instagram followers and I have not found an alternative.

Start with the Instagram page URL in cell A1:

https://www.instagram.com/benlcollins/

Then, this formula in cell B1 to extract the follower metadata (this may or may not work):

=IMPORTXML(A1,"//meta[@name='description']/@content")

This extracts the following info: “230 Followers, 259 Following, 465 Posts – See Instagram photos and videos from Ben Collins (@benlcollins)”

Next step is to combine this with REGEX to extract the followers for example. Here’s the formula to do that (still assuming url in cell A1):

=INDEX(REGEXEXTRACT(REGEXEXTRACT(LOWER(IMPORTXML(A1,"//meta[@name='description']/@content")),"([0-9km,.]+)( followers)"),"([0-9,.]+)([km]?)"),,1) * SWITCH(INDEX(REGEXEXTRACT(REGEXEXTRACT(LOWER(IMPORTXML(A1,"//meta[@name='description']/@content")),"([0-9km,.]+)( followers)"),"([0-9,.]+)([km]?)"),,2),"k",1000,"m",1000000,1)

This deals with any accounts that have abbreviated thousands (k) or millions (m) notations.

Alternative Approach

The following formulas to extract account metrics appear to only work for the instagram account when you are logged in. It makes use of the QUERY function, SPLIT function and INDEX function to do data wrangling inside the formula.

Here’s the number of followers:

=REGEXEXTRACT(INDEX(SPLIT(QUERY(IMPORTDATA(A1),"select Col1 limit 1 offset 181"),""""),1,2),"[\d,]+")

Here’s the number following:

=REGEXEXTRACT(QUERY(IMPORTDATA(A1),"select Col2 limit 1 offset 181"),"[\d,]+")

Here’s the number of posts:

=REGEXEXTRACT(QUERY(IMPORTDATA(A1),"select Col3 limit 1 offset 181"),"[\d,]+")

The following screenshot shows these formulas:

instagram data

See the Instagram Import Sheet.

^ Back to Contents


youtube logo Import YouTube data

Start with the YouTube channel URL in cell A1:

https://www.youtube.com/benlcollins

To get the number of subscribers to a YouTube channel, use this formula in cell B1:

=VALUE(INDEX(REGEXEXTRACT(LOWER(INDEX(REGEXEXTRACT(INDEX(IMPORTXML(A1,"//div[@class='primary-header-actions']"),1,1),"(Unsubscribe)([0-9kmKM.]+)"),1,2)),"([0-9,.]+)([km]?)"),,1) * SWITCH(INDEX(REGEXEXTRACT(LOWER(INDEX(REGEXEXTRACT(INDEX(IMPORTXML(A1,"//div[@class='primary-header-actions']"),1,1),"(Unsubscribe)([0-9kmKM.]+)"),1,2)),"([0-9,.]+)([km]?)"),,2),"k",1000,"m",1000000,1))

See the YouTube Import Sheet.

^ Back to Contents


pinterest logo Import Pinterest data

In cell A1, enter the following URL, again replacing benlcollins with the profile you’re interested in:

https://www.pinterest.com/bencollins/

Then in the adjacent cell, B1, enter the following formula:

=IMPORTXML(A1,"//meta[@property='pinterestapp:followers']/@content")

to get the following output (screenshot shows older version of the formula, latest one is above and in the template file):

pinterest data

Note, you can also get hold of the profile metadata with the import formulas, as follows:

=IMPORTXML(A1,"//meta[@name='description']/@content")

See the Pinterest Import Sheet.

^ Back to Contents


alexa logo Import Alexa ranking data

Here there are two metrics I’m interested in – a site’s Global rank and a site’s US rank.

Global Rank

To get the Global rank for your site, enter your URL into cell A1 (replace benlcollins.com):

http://www.alexa.com/siteinfo/benlcollins.com/

and use the following helper formula in cell B1:

=QUERY(ArrayFormula(QUERY(IMPORTDATA(A1),"select Col1") & QUERY(IMPORTDATA(A1),"select Col2")),"select * limit 1 offset " & MATCH(FALSE,ArrayFormula(ISNA(REGEXEXTRACT(QUERY(IMPORTDATA(A1),"select Col1") & QUERY(IMPORTDATA(A1),"select Col2"),"Global rank icon.{10,}"))),0)+1)

and then extract the rank in cell C1:

=VALUE(REGEXEXTRACT(B1,"[\d]{3,}"))

US Rank

Assuming you have the Alexa URL in cell A1 again, then the US rank is extracted with this helper formula:

=QUERY(ArrayFormula(QUERY(IMPORTDATA(A1),"select Col1") & QUERY(IMPORTDATA(A1),"select Col2")),"select * limit 1 offset " & MATCH(FALSE,ArrayFormula(ISNA(REGEXEXTRACT(QUERY(IMPORTDATA(A1),"select Col1") & QUERY(IMPORTDATA(A1),"select Col2"),"title='United States Flag'.alt.{50,}"))),0))

and this formula to extract the actual rank value:

=VALUE(REGEXEXTRACT(B1,"[\d]{3,}"))

The following screenshot shows these formulas:

alexa data

See the Alexa Ranking Import Sheet.

^ Back to Contents


Build Business Dashboards With Google Sheets

Digital marketing dashboard in Google Sheets
  • Learn how to build beautiful, interactive dashboards in my online course.
  • 9+ hours of video content, lifetime access and copies of all the finished dashboard templates.
  • Learn more

quora logo Import Quora data

In this instance, I’ve imported the number followers Barack Obama has on Quora.

Quora is a little bit different because I need to use the URL and the profile name in my formula, so I’ve kept them in separate cells for that purpose. So in cell A1, add the generic Quora URL:

https://www.quora.com/profile/

And then in cell B1, add the profile name:

Barack-Obama-44

Then the formula in C1 to get the number of followers is:

=VALUE(QUERY(IMPORTXML(A1&B1,"//a[@href='/profile/"&B1&"/followers']"),"select Col2"))

The following screenshot shows this formula:

quora data

See the Quora Import Sheet.

^ Back to Contents


reddit logo Import Reddit data

Here, I’m using the funny subreddit as my example.

In A1:

https://www.reddit.com/r/funny/

To get the number of followers of this subreddit, use this formula in cell B1:

=IMPORTXML(A1,"//span[@class='subscribers']/span[@class='number']")

Bonus: To get the number of active viewers of this subreddit:

=IMPORTXML(A1,"//p[@class='users-online']/span[@class='number']")

The following screenshot shows these formulas:

reddit data

See the Reddit Import Sheet.

^ Back to Contents


spotify logo Import Spotify monthly listeners

Here’s a method for extracting the number of followers an artist has on the music streaming site Spotify.

First, find your favorite artist on Spotify: https://open.spotify.com/browse/featured

Copy the URL into cell A1 (it’ll look like this):

https://open.spotify.com/artist/2ye2Wgw4gimLv2eAKyk1NB

(This is Metallica, yeah ?)

Then put the following formula into cell A2 to extract the monthly listeners:

=N(INDEX(IMPORTXML(A1,"//h3"),2))

See the Spotify Import Sheet.

To get Spotify playlist data, add the playlist URL into cell A1:

https://open.spotify.com/playlist/37i9dQZF1DX1lVhptIYRda

And use this formula to extract the number of songs and likes:

=QUERY(SPLIT(REGEXEXTRACT(INDEX(IMPORTXML(A1,"//@content"),5),"^(?:[a-zA-Z. ]+ · Playlist · )([0-9]+ songs · [0-9.KM]+ likes)")," · "),"select Col1, Col3")

^ Back to Contents


soundcloud logo Import Soundcloud data

Start with the Soundcloud page URL in cell A1, e.g.

https://soundcloud.com/fleecemusic

Here is the formula to extract page likes:

=ArrayFormula(VALUE(REGEXEXTRACT(QUERY(SORT(IFERROR(REGEXEXTRACT( IMPORTXML(A1,"//script"),"followers_count..\d{1,}"),""),1,FALSE),"select * limit 1"),"\d{1,}")))

Alternative formula:

Here is an alternative formula to extract the page metadata, which includes the likes:

=IMPORTXML(A1,"//meta[@name='description']/@content")

the formula to extract likes is:

=VALUE(REGEXEXTRACT(REGEXEXTRACT(SUBSTITUTE( IMPORTXML(A1,"//meta[@name='description']/@content"),",",""),"\d{1,}.Followers"),"\d{1,}"))

and to extract the “talking about” number:

=VALUE(REGEXEXTRACT(REGEXEXTRACT(SUBSTITUTE( IMPORTXML(A1,"//meta[@name='description']/@content"),",",""),"\d{1,}.Tracks"),"\d{1,}"))

The following screenshot shows these formulas:

soundcloud data

See the Soundcloud Import Sheet.

^ Back to Contents


gtmetrix_logo Import GTmetrix data

GTmetrix is a website that analyzes website performance.

You need to grab the correct URL before you can start scraping the data. So navigate to the GTmetrix site and enter the URL and hit analyze. You’ll end up with a URL like this:

https://gtmetrix.com/reports/www.benlcollins.com/BcHv78bP

Those last 8 characters (“BcHv78bP”) appear to be unique each time you run an analysis, so you’ll have to do this step manually.

Then in column B, I use this formula to extract the Page Speed Score and YSlow Score, into cells B1 and B2:

=ArrayFormula(ABS(IMPORTXML(A1,"//span[@class='report-score-percent']")))

and this formula in cell B3, to get the page details (Fully Loaded Time, Total Page Size and Requests) in cells B3, B4 and B5:

=IMPORTXML(A1,"//span[@class='report-page-detail-value']")

The following screenshot shows these formulas:

gtmetrix data

See the GTmetrix Import Sheet.

^ Back to Contents


Bitly logoImport Bitly click data

Bitly is a service for shortening urls. They provide metrics for how many clicks you’ve had on each bitly link, e,g.

Bitly link metric data for import to Google Sheets

Taking a standard Bitly link (e.g. http://bitly.com/2mmW1lr) and appending a “+” to it will take you to the dashboard page, with the metrics. Then we can use the import data function, a query function and a REGEX function to extract the click metrics.

User clicks are:

=VALUE(REGEXEXTRACT(QUERY(IMPORTDATA(A9&"+"),"select Col1 limit 1"),"(?:user_clicks...)([0-9]+)"))

and global clicks are:

=VALUE(REGEXEXTRACT(QUERY(IMPORTDATA(A9&"+"),"select Col5"),"(?:global_clicks:.)([0-9]+)"))

Clicks from the Bitly network are then simply the user clicks subtracted from the global clicks.

The following screenshot shows these formulas:

Bitly data import in Google Sheets

See the Bitly Import Sheet.

^ Back to Contents


linkedin logo Import Linkedin data

This formula is no longer working for extracting Linkedin followers and I have not found an alternative.

In cell A1:

https://www.linkedin.com/in/benlcollins/

This formula used to work to get the number of Linkedin followers, but no longer:

=QUERY(IMPORTXML(A1,"//div[@class='member-connections']"),"select Col1")

and the output:

linkedin import

There is no example sheet for Linkedin since the formula is no longer working.

^ Back to Contents


cancel icon Sites that don’t work and why not

I’ve tried the following sites but the IMPORT formulas are unable to extract the social media statistics:

  • Linkedin (see above)
  • Similar Web
  • Twitch
  • Mobcrush
  • Crunchbase
  • Angel.co
  • Majestic SEO

These are all modern sites built using front-end, client-side Javascript frameworks, so the IMPORT formulas can’t extract any data because the page is built dynamically in browser as it’s loaded up. The IMPORT formulas work fine on sites built in the traditional fashion, with lots of well formed HTML tags, where the social media statistics are embedded into the site markup that is passed from the server.

Compare this screenshot of the source code for Mobcrush, built using Angular JS it looks like (click to enlarge):

Angular front end

versus what the source code looks for this page on my website (click to enlarge):

benlcollins code

You can see the code for my site has lots of tags which the IMPORT formulas can parse, whereas the other site’s code does not.

If anyone knows of any clever way to get around this, do share!

Otherwise, you’re next option is to venture down the API route. Yes, this involves coding, but it’s not as hard as you think.

I’ll be posting some API focussed articles soon. In the meantime, check out my post on how to get started with APIs, or for a peak at what’s coming, take a look at my Apps Script + API repo on GitHub.

Loading error

Also, even when these formulas are working, they can be temperamental. If you work with them a lot, sooner or later you’ll find yourself hitting this loading issue all the time, where the formulas stop displaying any results:

Loading error

^ Back to Contents


settings logo Closing thoughts

These formulas are unstable and will sometimes display an error message.

I’ve found that adding or removing the final “/” from the URL can sometimes get the formula working again (the issue is to do with caching).

I can make no guarantee that these will work for you or into the future. Whilst researching this article, I came across several older articles where many of the formulas no longer work. So things change!

To summarize: Caveat Emptor!

^ Back to Contents


link icon Resources

^ Back to Contents


As always, leave any comments, corrections or request other social media statistics below.

Icons from Freepik.

The Complete Guide to Simple Automation using Google Sheets Macros

Google Sheets Macros are small programs you create inside of Google Sheets without needing to write any code.

They’re used to automate repeatable tasks. They work by recording your actions as you do something and saving these actions as a “recipe” that you can re-use again with a single click.

For example, you might apply the same formatting to your charts and tables. It’s tedious to do this manually each time. Instead you record a macro to apply the formatting at the click of a button.

In this article, you’ll learn how to use them, discover their limitations and also see how they’re a great segue into the wonderful world of Apps Script coding!

Contents

  1. What are Google Sheets macros?
  2. Why should you use macros?
  3. How to create your first macro
  4. Other options
  5. Best Practices for Google Sheets Macros
  6. Limitations of Google Sheets Macros
  7. A peek under the hood of Google Sheets Macros
  8. Example of Google Sheets Macros
  9. Resources

1. What are Google Sheets macros?

Think of a typical day at work with Google Sheets open. There are probably some tasks you perform repeatedly, such as formatting reports to look a certain way, or adding the same chart to new sales data, or creating that special formula unique to your business.

They all take time, right?

They’re repetitive. Boring too probably. You’re just going through the same motions as yesterday, or last week, or last month. And anything that’s repetitive is a great contender for automating.

This is where Google Sheets macros come in, and this is how they work:

  • Click a button to start recording a macro
  • Do your stuff
  • Click the button to stop recording the macro
  • Redo the process whenever you want at the click of a button

They really are that simple.

^ Back to Contents

2. Why should you use macros in Google Sheets?

There’s the obvious reason that macros in Google Sheets can save you heaps of time, allowing you to focus on higher value activity.

But there’s a host of other less obvious reasons like: avoiding mistakes, ensuring consistency in your work, decreased boredom at work (corollary: increased motivation!) and lastly, they’re a great doorway into the wonderful world of Apps Script coding, where you can really turbocharge your spreadsheets and Google Workspace work.

^ Back to Contents

3. Steps to record your first macro

Let’s run through the process of creating a super basic macro, in steps:

1) Open a new Google Sheet (pro-tip 1: type sheets.new into your browser to create a new Sheet instantly, or pro-tip 2: in your Drive folder hit Shift + s to create a new Sheet in that folder instantly).

Type some words in cell A1.

2) Go to the macro menu: Tools > Macros > Record macro

Google Sheets macro menu

3) You have a choice between Absolute or Relative references. For this first example, let’s choose relative references:

Macro with relative reference

Absolute references apply the formatting to the same range of cells each time (if you select A1:D10 for example, it’ll always apply the macro to these cells). It’s useful if you want to apply steps to a new batch of data each time, and it’s in the same range location each time.

Relative references apply the formatting based on where your cursor is (if you record your macro applied to cell A1, but then re-run the macro when you’ve selected cell D5, the macro steps will be applied to D5 now). It’s useful for things like formulas that you want to apply to different cells.

4) Apply some formatting to the text in cell A1 (e.g. make it bold, make it bigger, change the color, etc.). You’ll notice the macro recorder logging each step:

Macro logging step

5) When you’ve finished, click SAVE and give your Macro a name:

Save macro

(You can also add a shortcut key to allow quick access to run your macro in the future.)

Click SAVE again and Google Sheets will save your macro.

6) Your macro is now available to use and is accessed through the Tools > Macros menu:

select macro menu

7) The first time you run the macro, you’ll be prompted to grant it permission to run. This is a security measure to ensure you’re happy to run the code in the background. Since you’ve created it, it’s safe to proceed.

First, you’ll click Continue on the Authorization popup:

Macro authorization

Then select your Google account:

Macro choose Google account

Finally, review the permissions, and click Allow:

Macro grant permissions

8) The macro then runs and repeats the actions you recorded on the new cell you’ve selected!

You’ll see the following yellow status messages flash across the top of your Google Sheet:

Macro running script

Macro finished script

and then you’ll see the result:

Macro result

Woohoo!

Congratulations on your first Google Sheets macro! You see, it was easy!

Here’s a quick GIF showing the macro recording process in full:

Recording a macro

And here’s what it looks like when you run it:

Run your macro

^ Back to Contents

4. Other options

4.1 Macro Shortcuts

This is an optional feature when you save your macro in Google Sheets. They can also be added later via the Tools > Macros > Manage macros menu.

Shortcuts allow you to run your macros by pressing the specific combination of keys you’ve set, which saves you further time by not having to click through the menus.

Any macro shortcut keys must be unique and you’re limited to a maximum of 10 macro shortcut keys per Google Sheet.

Macro shortcut

In the above example, I could run this macro by pressing:

⌘ + option + shift + 1

keys at the same time (takes practice ?). Will be a different key combo on PC/Chromebooks.

4.2 Deleting macros

You can remove Google Sheets macros from your Sheet through the manage macros menu: Tools > Macros > Manage macros

Under the list of your macros, find the one you want to delete. Click the three vertical dots on right side of macro and then choose Remove macro:

remove macro

4.3 Importing other macros

Lastly, you can add any functions you’ve created in your Apps Script file to the Macro menu, so you can run them without having to go to the script editor window. This is a more advanced option for users who are more comfortable with writing Apps Script code.

import function to macro menu

This option is only available if you have functions in your Apps Script file that are not already in the macro menu. Otherwise it will be greyed out.

^ Back to Contents

5. Best Practices for Google Sheets Macros

Use the minimum number of actions you can when you record your macros to keep them as performant as possible.

For macros that make changes to a single cell, you can apply those same changes to a range of cells by highlighting the range first and then running the macro. So it’s often not necessary to highlight entire ranges when you’re recording your macros.

^ Back to Contents

6. Limitations of Google Sheets Macros

Macros are bound to the Google Sheet in which they’re created and can’t be used outside of that Sheet. Similarly, macros written in standalone Apps Script files are simply ignored.

Macros are not available for other Google Workspace tools like Google Docs, Slides, etc. (At least, not yet.)

You can’t distribute macros as libraries or define them in Sheets Add-ons. I hope the distribution of macros is improved in the future, so you can create a catalog of macros that is available across any Sheets in your Drive folder.

^ Back to Contents

7. A peek under the hood of Google Sheets Macros

Behind the scenes, macros in Google Sheets converts your actions into Apps Script code, which is just a version of Javascript run in the Google Cloud.

If you’re new to Apps Script, you may want to check out my Google Apps Script: A Beginner’s Guide.

If you want to take a look at this code, you can see it by opening the script editor (Tools > Script editor or Tools > Macros > Manage macros).

You’ll see an Apps Script file with code similar to this:

/** @OnlyCurrentDoc */

function FormatText() {
  var spreadsheet = SpreadsheetApp.getActive();
  spreadsheet.getActiveRangeList().setFontWeight('bold')
  .setFontStyle('italic')
  .setFontColor('#ff0000')
  .setFontSize(18)
  .setFontFamily('Montserrat');
};

Essentially, this code grabs the spreadsheet and then grabs the active range of cells I’ve selected.

The macro then makes this selection bold (line 5), italic (line 6), red (line 7, specified as a hex color), font size 18 (line 8), and finally changes the font family to Montserrat (line 9).

The video at the top of this page goes into a lot more detail about this Apps Script, what it means and how to modify it.

Macros in Google Sheets are a great first step into the world of Apps Script, so I’d encourage you to open up the editor for your different macros and check out what they look like.

(In case you’re wondering, the line /** @OnlyCurrentDoc */ ensures that the authorization procedure only asks for access to the current file where your macro lives.)

^ Back to Contents

8. Examples of Google Sheets Macros

8.1 Formatting tables

Record the steps as you format your reporting tables, so that you can quickly apply those same formatting steps to other tables. You’ll want to use Relative references so that you can apply the formatting wherever your table range is (if you used absolute then it will always apply the formatting to the same range of cells).

Check out the video at the top of the page to see this example in detail, including how to modify the Apps Script code to adjust for different sized tables.

8.2 Creating charts

If you find yourself creating the same chart over and over, say for new datasets each week, then maybe it’s time to encapsulate that in a macro.

Record your steps as you create the chart your first time so you have it for future use.

The video at the top of the page shows an example in detail.


The following macros are intended to be copied into your Script Editor and then imported to the macro menu and run from there.

8.3 Convert all formulas to values on current Sheet

Open your script editor (Tools > Script editor). Copy and paste the following code onto a new line:

// convert all formulas to values in the active sheet
function formulasToValuesActiveSheet() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getDataRange();
  range.copyValuesToRange(sheet, 1, range.getLastColumn(), 1, range.getLastRow());
};

Back in your Google Sheet, use the Macro Import option to import this function as a macro.

When you run it, it will convert any formulas in the current sheet to values.

8.4 Convert all formulas to values in entire Google Sheet

Open your script editor (Tools > Script editor). Copy and paste the following code onto a new line:

// convert all formulas to values in every sheet of the Google Sheet
function formulasToValuesGlobal() {
  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
  sheets.forEach(function(sheet) {
    var range = sheet.getDataRange();
    range.copyValuesToRange(sheet, 1, range.getLastColumn(), 1, range.getLastRow());
  });
};

Back in your Google Sheet, use the Macro Import option to import this function as a macro.

When you run it, it will convert all the formulas in every sheet of your Google Sheet into values.

8.5 Sort all your sheets in a Google Sheet alphabetically

Open your script editor (Tools > Script editor). Copy and paste the following code onto a new line:

// sort sheets alphabetically
function sortSheets() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = spreadsheet.getSheets();
  var sheetNames = [];
  sheets.forEach(function(sheet,i) {
    sheetNames.push(sheet.getName());
  });
  sheetNames.sort().forEach(function(sheet,i) {
    spreadsheet.getSheetByName(sheet).activate();
    spreadsheet.moveActiveSheet(i + 1);
  });
};

Back in your Google Sheet, use the Macro Import option to import this function as a macro.

When you run it, it will sort all your sheets in a Google Sheet alphabetically.

8.6 Unhide all rows and columns in the current Sheet

Open your script editor (Tools > Script editor). Copy and paste the following code onto a new line:

// unhide all rows and columns in current Sheet data range
function unhideRowsColumnsActiveSheet() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getDataRange();
  sheet.unhideRow(range);
  sheet.unhideColumn(range);
}

Back in your Google Sheet, use the Macro Import option to import this function as a macro.

When you run it, it will unhide any hidden rows and columns within the data range. (If you have hidden rows/columns outside of the data range, they will not be affected.)

8.7 Unhide all rows and columns in entire Google Sheet

Open your script editor (Tools > Script editor). Copy and paste the following code onto a new line:

// unhide all rows and columns in data ranges of entire Google Sheet
function unhideRowsColumnsGlobal() {
  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
  sheets.forEach(function(sheet) {
    var range = sheet.getDataRange();
    sheet.unhideRow(range);
    sheet.unhideColumn(range);
  });
};

Back in your Google Sheet, use the Macro Import option to import this function as a macro.

When you run it, it will unhide any hidden rows and columns within the data range in each sheet of your entire Google Sheet.

8.8 Set all Sheets to have a specific tab color

Open your script editor (Tools > Script editor). Copy and paste the following code onto a new line:

// set all Sheets tabs to red
function setTabColor() {
  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
  sheets.forEach(function(sheet) {
    sheet.setTabColor("ff0000");
  });
};

Back in your Google Sheet, use the Macro Import option to import this function as a macro.

When you run it, it will set all of the tab colors to red.

Want a different color? Just change the hex code on line 5 to whatever you want, e.g. cornflower blue would be 6495ed

Use this handy guide to find the hex values you want.

8.9 Remove any tab coloring from all Sheets

Open your script editor (Tools > Script editor). Copy and paste the following code onto a new line:

// remove all Sheets tabs color
function resetTabColor() {
  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
  sheets.forEach(function(sheet) {
    sheet.setTabColor(null);
  });
};

Back in your Google Sheet, use the Macro Import option to import this function as a macro.

When you run it, it will remove all of the tab colors from your Sheet (it sets them back to null, i.e. no value).

Here’s a GIF showing the tab colors being added and removed via Macros (check the bottom of the image):

color tabs with Macros

8.10 Hide all sheets apart from the active one

Copy and paste this code into your script editor and import the function into your Macro menu:

function hideAllSheetsExceptActive() {
  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
  sheets.forEach(function(sheet) {
    if (sheet.getName() != SpreadsheetApp.getActiveSheet().getName()) 
      sheet.hideSheet();
  });
};

Running this macro will hide all the Sheets in your Google Sheet, except for the one you have selected (the active sheet).

8.11 Unhide all Sheets in your Sheet in one go

Open your script editor (Tools > Script editor). Copy and paste the following code onto a new line:

function unhideAllSheets() {
  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
  sheets.forEach(function(sheet) {
    sheet.showSheet();
  });
};

Back in your Google Sheet, use the Macro Import option to import this function as a macro.

When you run it, it will show any hidden Sheets in your Sheet, to save you having to do it 1-by-1.

Here’s a GIF showing how the hide and unhide macros work:

hide unhide sheets with macros

You can see how Sheet6, the active Sheet, is the only one that isn’t hidden when the first macro is run.

8.12 Resetting Filters

Ok, saving the best to last, this is one of my favorite macros! 🙂

I use filters on my data tables all the time, and find it mildly annoying that there’s no way to clear all your filters in one go. You have to manually reset each filter in turn (time consuming, and sometimes hard to see which columns have filters when you have really big datasets) OR you can completely remove the filter and re-add from the menu.

Let’s create a macro in Google Sheets to do that! Then we can be super efficient by running it with a single menu click or even better, from a shortcut.

Open your script editor (Tools > Script editor). Copy and paste the following code onto a new line:

// reset all filters for a data range on current Sheet
function resetFilter() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var range = sheet.getDataRange();
  range.getFilter().remove();
  range.createFilter();
}

Back in your Google Sheet, use the Macro Import option to import this function as a macro.

When you run it, it will remove and then re-add filters to your data range in one go.

Here’s a GIF showing the problem and macro solution:

Macro to reset filters

^ Back to Contents

9. Resources

If you’re interested in taking things further, check out the following resources for getting started with Apps Script:

Macro reference guide in Google Docs help

Macro reference guide in the Google Developer documentation

And if you want to really start digging into the Apps Script code, you’ll want to bookmark the Google documentation for the Spreadsheet Service.

Finally, all of this macro code is available here on GitHub.

How To Connect Google Sheets To A Database, Using Apps Script

This is a guest post from Mike Ritchie, co-founder of Seekwell.io, which adds SQL to the apps you need it in.

Google Sheets is great for quickly spinning up dashboards and analysis, but getting raw data into Sheets from databases can be tedious.

In this post we cover a few ways to get data from your SQL database into Google Sheets.

Google Sheets Database Connection With Apps Script

Sheets comes with a built-in app development platform called “Apps Script”.

Based on JavaScript, it covers a lot of the tasks you’d use VBA for in Excel.

App Script comes with a JDBC Service that lets you connect to MySQL, Microsoft SQL Server, and Oracle databases.

Steps To Connect Google Sheets To A Database

1) Open the Script Editor in Sheets using “Tools” → “Script editor”. Or just copy this Sheet here.

How To Connect Google Sheets To A Database
Access Apps Script under the menu Tools > Script editor

2) Replace “Code.gs” with the code here. (Skip this if you copied the Sheet above)

3) We included credentials for SeekWell’s demo MySQL database. To connect to your database, replace the six fields below. Note you’ll need to whitelist Google’s IP addresses.

var HOST = 'yourhostname'
var PORT = '3306 or your port'
var USERNAME = 'yourusername'
var PASSWORD = 'yourpassword'
var DATABASE = 'youdatabasename'
var DB_TYPE = 'mysql or your type'

4) You might also want to change the MAXROWS, but you don’t go too crazy, Sheets has a hard limit of 10 million cells and the query will take longer to run with more rows.

5) Save the file and refresh / refresh the Sheet. You’ll see a new menu option of “SeekWell Lite” show up.

6) The script is set up to read the query from query!A2 and write the results to your active cell, so you’ll need to add a sheet called “query” and add the query below in the cell query!A2 (skip if you copied the Sheet above).

SELECT *
FROM dummy.users
LIMIT 100

7) Go back to Sheet1, click in cell C4 (or any other cell) and click “SeekWell Lite” → “Run SQL”.

In a few moments you’ll see the data show up!

A few problems with this approach

You need to store your password in plain text in the Code.gs file.

Sharing the script with your team and adding the script to different Sheets is a bit of a pain. You can publish an addon, but that comes with some overhead.

And scheduling / automating refreshes can be cumbersome when you need many different queries going to many different Sheets.

Google’s JDBC service doesn’t work for Postgres, Snowflake or RedShift and requires a long list of whitelisted IP’s. It also doesn’t support SSH.

Alternatives to Google Sheets database connections with App Script

Python

If you’re comfortable with Python, you can put together a program using Pandas and the Sheets API. Pandas has great SQL support built in.

SaaS Products

A lot of people hate paying for things they can do for free, but you should always do some napkin math when making the “build vs. buy” decision.

In the case of automating reports, the ROI can be pretty high, especially if you have several daily, hourly, or near real time dashboards you need to keep updated. ActionDesk did a good overview of the options out there.


This is a guest post written by Mike Ritchie. Mike is the co-founder of Seekwell and has over 15 years experience in analytics.

SeekWell features include:

  • Takes < 2 minutes to get your first schedule set up
  • A shared code repository with every query anyone on your team has ever written
  • Beautiful query editor with autocomplete and snippets
  • Ability to automate alerts via Slack and email
  • Support for MySQL, Postgres, Snowflake, Redshift, Salesforce, and SQL Server

18 Google Sheets Formulas Tips & Techniques You Should Know

Mastering Google Sheets formulas is more than just knowing the functions themselves and how to combine them.

True mastery comes when you know all of the little, hidden shortcuts and tricks built in to Google Sheets to help you with your formulas. Individually they may not seem like much, but combine them together in your toolkit and you’ll be more efficient and effective when working with Google spreadsheet formulas.

How many of these Google Sheets Formulas Tips & Techniques do you know?

Contents

  1. F4 Key
  2. F2 To Edit Cell
  3. Shift + Enter To Edit Cell
  4. Escape To Exit A Formula
  5. Move To The Front Or End Of Your Google Sheets Formulas
  6. Function Helper Pane
  7. Colored Ranges in Google Sheets Formulas
  8. F2 To Highlight Specific Ranges In Your Google Sheets Formulas
  9. Function Name Drop-Down
  10. Tab To Auto-Complete
  11. Adjust The Formula Bar Width
  12. Quick Aggregation Toolbar
  13. Quick Fill Down
  14. Know How To Create An ArrayFormula
  15. Array Literals With Curly Brackets
  16. Multi-line Google Sheets Formulas
  17. Comments In Google Spreadsheet Formulas
  18. Use The Onion Approach

Tips For Google Sheets Formulas

1. F4 Key

Undoubtedly one of the most useful Google Sheets formula shortcuts to learn.

Press the F4 key to toggle between relative and absolute references in ranges in your Google Sheets formulas.

F4 to switch between relative and absolute referencing

It’s WAY quicker than clicking and typing in the dollar ($) signs to change a reference into an absolute reference.

Back to top

2. F2 To Edit Cell

Have you ever found yourself needing to copy part of a Google Sheets formula to use elsewhere? This is a shortcut to bring up the formula in a cell.

Start by selecting a cell containing a formula.

Press the F2 key to enter into the formula:

F2 shortcut key to enter Google Sheets Formula

Back to top

3. Shift + Enter To Edit Cell

Shift + Enter is another shortcut to enter into the Google Sheets formula edit view.

Back to top

4. Escape To Exit A Formula

Have you ever found yourself trying to click out of your formula, but Sheets thinks you want to highlight a new cell and it messes up your formula?

Press the Escape key to exit the formula view and return to the result view.

Any changes are discarded when you press the Escape key (to save changes you just hit the usual Return key).

Back to top

5. Move To The Front Or End Of Your Google Sheets Formulas

Here’s another quick trick that’s helpful for longer Google spreadsheets formulas:

When you’re inside the formula view, press the Up arrow to go to the front of your formula (in front of the equals sign).

Similarly, pressing the Down arrow takes you to the last character in your formula.

Up Down Arrow Keys in Google Sheets Formula

Back to top

6. Function Helper Pane

Learn to read the function helper pane!

Google Sheets Formula Helper Pane

You can press the “X” to remove the whole pane if it’s getting it the way. Or you can minimize/maximize with the arrow in the top right corner.

The best feature of the formula pane is the yellow highlighting it adds to show you which section of your function you are in. E.g. in the image above I’m looking at the “[headers]” argument.

There is information about what data the function is expecting and even a link to the full Google documentation for that function.

If you’ve hidden the function pane, or you can’t see it, look for the blue question mark next to the equals sign of your formula. Click that and it will restore the function helper pane.

Back to top

7. Colored Ranges in Google Sheets Formulas

Helpfully Google Sheets highlights ranges in your formulas and in your actual Sheet with matching colors. It applies different colors to each unique range in your formula.

Google Sheets Function highlighting

Back to top

8. F2 To Highlight Specific Ranges In Your Google Sheets Formulas

As mentioned in Step 2, you press the F2 key to enter the formula view of a cell with a formula in.

However, it has another useful property. If you position your cursor over a range of data in your formula and then press the F2 key, it will highlight that range of data for you:

F2 to highlight range in Google Sheets formula

Back to top

9. Function Name Drop-Down

A great way to discover new functions is to simply type a single letter after an equals sign, and then browse what comes up:

Google Sheets Function Drop-Down List

Scroll up and down the list with the Up and Down arrows, and then click on the function you want.

Back to top

10. Tab To Auto-Complete Function Name

When you’re using the function drop-down list in the tip above, press the tab key to auto-complete the function name (based on whatever function is highlighted).

Back to top

11. Adjust The Formula Bar Width

Google Sheets Formula Bar Width

An easy one this! Grab the base of the formula bar until you see the cursor change into a little double-ended arrow. Then click and drag down to make the formula bar as wide as you want.

Back to top

12. Quick Aggregation Toolbar

Highlight a range of data in your Sheet and check out the quick aggregation tool in the bottom toolbar of your Sheet (bottom right corner).

Quick Aggregation Toolbar

Quickly find out the aggregate measures COUNT, COUNT NUMBERS, SUM, AVERAGE, MIN and MAX, without needing to create functions.

Back to top

13. Quick Fill Down

Double click to copy formula

To copy the formula quickly down the column, double-click the blue mark in the corner of the highlighted cell, shown by the red arrow. This will copy the cell contents and format down as far as the contiguous range in preceding column (column A in this case).

An alternative way to quickly fill in a column is to highlight the range you want to fill, e.g.:

Quickly enter data in Google Sheets

Then press Ctrl + D (PC and Chromebook) or Cmd + D (Mac) to copy the contents and format down the whole range, like so:

Quickly enter data in Google Sheets

You can also do this with Ctrl + Enter (PC and Chromebook) or Cmd + Enter (Mac), which will fill down the column.

Back to top

14. Know How To Create An ArrayFormula

Array Formulas in Google Sheets are powerful extensions to regular formulas, allowing you to work with ranges of data rather than individual pieces of data.

Per the official definition, array formulas enable the display of values returned into multiple rows and/or columns and the use of non-array functions with arrays.

In a nutshell: whereas a normal formula outputs a single value, array formulas output a range of cells!

We need to tell Google Sheets we want a formula to be an Array Formula. We do this in two ways:

  1. Hit Ctrl + Shift + Enter (PC/Chromebook) or Cmd + Shift + Enter (on a Mac) and Google Sheets will add the ArrayFormula wrapper
  2. Alternatively, type in the word ArrayFormula and add brackets to wrap your formula

Back to top

15. Array Literals With Curly Brackets

Have you ever used the curly brackets, or ARRAY LITERALS to use the correct nomenclature, in your formulas?

An array is a table of data. They can be used in the same way that a range of rows and columns can be used in your formulas. You construct them with curly brackets:

{ }

Commas separate the data into columns on the same row.

Semi-colons create a new row in your array.

(Please note, if you’re based in Europe, the syntax is a little different. Find out more here.)

This formula, entered into cell A1, will create a 2 by 2 array that puts data in the range A1 to B2:

= { 1 , 2 ; 3 , 4 }

The array component (in this example { 1 , 2 ; 3 , 4 } ) can be used as an input to other formulas.

One nice application of array literals is to create default values for cells in your Google Sheets.

Read more about arrays in Google Sheets (a.k.a. array literals).

Back to top

16. Multi-line Google Sheets Formulas

Press Ctrl + Enter inside the formula editor bar to add new lines to your formulas, to make them more readable. Note, you’ll probably want to widen the formula bar first, per tip 11.

Multi-line formula in Google Sheets

Back to top

17. Comments In Google Spreadsheet Formulas

Add comments to your formulas, using the N function.

N returns the argument provided as a number. If the argument is text, inside quotation marks, the N function returns 0.

So we can use it to add a comment like this:

=SUM(A1:A100) + N("Sums the first 100 rows of column A")

which is effectively the same as:

=SUM(A1:A100) + 0

which is just:

=SUM(A1:A100)

This tip is pretty esoteric, but it’s helpful for any really long Google spreadsheet formulas!

Back to top

18. Use The Onion Approach For Complex Formulas

Complex formulas are like onions on two counts: i) they have layers that you can peel back, and ii) they often make you cry 😭

Use The Onion Method To Approach Complex Formulas

If you’re building complex formulas, then I advocate a one-action-per-step approach. What I mean by this is build your formula in a series of steps, and only make one change with each step. So if you start with function A(range) in a cell, then copy it to a new cell before you nest it with B(A(range)), etc.

This lets you progress in a step-by-step manner and see exactly where your formula breaks down.

Similarly, if you’re trying to understand complex formulas, peel the layers back until you reach the core (which is hopefully a position you understand). Then, build it back up in steps to get back to the full formula.

For more detail about this approach, including examples and worksheets for each case, have a read of this post:

Use The Onion Method To Approach Complex Formulas

This is an updated version of an article that was previously published. We update our tutorials to ensure they’re useful for our readers.

Back to top