Get our FREE VBA eBook of the 30 most useful Excel VBA macros.

Automate Excel so that you can save time and stop doing the jobs a trained monkey could do.

Claim your free eBook

Auto refresh Power Query on parameter change

Auto-refresh Power Query Featured Image

A few days ago, a reader asked a question about using parameters in Power Query; they wanted to auto-refresh Power Query whenever a parameter changes.

“One question, how do you set the query to refresh automatically when a value changes.”

I’ve not tried this before, but I can understand the benefits.  It reduces the need to click Refresh and creates behavior that is closer in nature to standard Excel formulas.  So, it sounded like a question that deserved its own post.

This is the result we are trying to achieve:

Auto refresh Power Query

Download the example file

I recommend you download the example file for this post.  Then you’ll be able to work along with examples and see the solution in action, plus the file will be useful for future reference.

Download Icon
Download the file: 0013 Auto refresh Power

Auto refresh power query with a macro

There are two ways for Excel to trigger events when cell values change:

  1. User Defined Function (UDF)
  2. Worksheet change event

I love using UDFs to control objects in Excel, such as changing tab colors, or setting the min and max of a chart axis.  However, I tried a UDF for this auto-refresh scenario, but it just wasn’t stable and caused Excel to crash.  If you manage to achieve this, please let me know in the comments so we can all learn from your VBA mastery 🙂

That leaves option 2, the worksheet change event.

  1. Go into the Visual Basic Editor by clicking Developer -> Visual Basic (if you’ve not got the Developer ribbon visible, you can use the keyboard short cut Alt + F11).
    Developer - Visual Basic
  2. Open the code module for the worksheet that contains the parameter.   In the example file, the Query Output tab contains the cell with the parameter.
    Visual Basic Editor
  3. Copy the following code into the sheet module.
    Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = Me.Range("G6").Address _
        Or Target.Address = Me.Range("G3").Address _
        ActiveWorkbook.Connections("Query - SalesData").Refresh
    End If
    End Sub
  4. Next, adapt the code to your scenario by changing the following:
    The cell references (highlighted purple in the code above) are the cells containing your parameters.  In the example file, there are two parameters in cells G6 and G3.
    The name of the query (highlighted green in the code above) will be the string “Query – “ + name of the query to refresh.  In the example file, the query is called SalesData.  Therefore the full string is Query – SalesData
    If you need more or less parameters, then add or remove instances of the following line of code:

    Or Target.Address = Me.Range("G3").Address _
  5. Close the Visual Basic Editor

That’s it; now the macro is ready for use.  Change the parameter and watch the macro automatically update the query.

NOTES:Workbooks that contain macros cannot be saved as .xlsx files. Instead, we need to use the .xlsm format.

As standard Excel behavior, when a macro executes, the Undo stack is cleared.  Therefore you will not be able to use the Undo feature after the macro runs.

Another option – refresh every n minutes

Another option, which doesn’t quite meet the reader’s requirements, but which might meet yours, is to automatically refresh the query at set intervals.  Doing this:

    • Avoids macros and therefore we can use the standard .xlsx file type
    • Still avoids the need to click refresh
    • Won’t provide an instant update, so does not emulate formula behavior of automatically recalculating

To implement this:

  1. From the ribbon select Data -> Queries & Connections
    Data - Queries and Connections
  2. Right-click on the query and select Properties… from the menu.
    Query Properties
  3. Tick the Refresh Every n Minutes option and enter a time interval.
    Refresh every x minutes
  4. Click OK to close the Query Properties dialog box.

The query will now automatically refresh at the set interval.  It if meets your requirements, it is a better option than a macro.

What next?

If your query is loaded directly into a Pivot Table, then this post by Jon Acampora will be a good next step.

Or, if you want to know more about using the Power Query editor, check out this post.

Headshot Round

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn't until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).

Do you need help adapting this post to your needs?

I'm guessing the examples in this post don't exactly match your situation. We all use Excel differently, so it's impossible to write a post that will meet everybody's needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you're still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the 'Excel Ninja' in your office. It's amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it's clear and concise.  List all the things you've tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don't go yet, there is plenty more to learn on Excel Off The Grid.  Check out the latest posts:

18 thoughts on “Auto refresh Power Query on parameter change

  1. Tiago says:

    Hello. Could you help me please?
    I want to know if I set the refresh every n minutes on background, when I close the sheet, does it work or not?

    • Excel Off The Grid says:

      Hi Tiago – I don’t think it does. But why not just try it out and see what happens, then you’ll know for sure.

  2. Andrew Appleton says:

    Can I use this to refresh a second query on a different sheet? I’ve tried:

    Sub Worksheet_Change(ByVal Target As Range)

    If Target.Address = Me.Range(“G6”).Address _
    Or Target.Address = Me.Range(“G3”).Address _

    ActiveWorkbook.Connections(“Query – Query1”).Refresh
    ActiveWorkbook.Connections(“Query – Query2”).Refresh

    End If

    End Sub

    This doesn’t refresh Query2. No errors appear.

    • Excel Off The Grid says:

      Hi Andrew

      Yes, you can refresh a query on another page using this method.

      But it will only work if the query parameter is also pointing to the cell on the other page, or cell linked to the parameter. Otherwise it will keep refreshing the query using the same parameters.

  3. Shantanu Das says:

    Another option – refresh every n minutes
    Hi, hope you are doing good.
    I have created a report using power query and it is connected to a csv file. The report is saved in a SharePoint folder. I want that power query of the report should be be refreshed in every 30 minutes, so per as your tutorial I go the query and click on properties and set –refresh every 30 minutes. But unfortunately it didn’t work. Could you please tell me what is the problem here or what I am missing? I need to sort this urgently . Please reply at earliest.
    Thanks in Advance!

  4. Marco says:

    Greetings, first of all, thanks for the amazing article. I learned so much from this real-world example.

    I am trying to achieve the VB-script option, but i’m struggling. Maybe you can assist me with the debug. I am trying to adapt the refresh-code.

    My case:
    – I have an Excel which keeps track of hours worked by volunteers. These hours are noted down in a table on the ‘hours worked’ sheet.
    – I have 1 output sheet (like in the example)
    – On the output sheet, I have 13 tables, one for each volunteer. The table uses a query to retrieve all their specific worked hours from the ‘hours worked’ tab.
    -Each table has their own connections. I renamed all the connections ‘Hours_volunteer1’ to ‘Hours_volunteer13’.
    -Each table has 1 input variable, the name of the volunteer.

    I attempted to adjust the VBA script in the following way:
    Sub Worksheet_Change(ByVal Target As Range)

    If Target.Address = Me.Range(“J2”).Address _

    ActiveWorkbook.Connections(“Query – Hours_volunteer1”).Refresh

    ElseIf Target.Address = Me.Range(“J14”).Address _

    ActiveWorkbook.Connections(“Query – Hours_volunteer2”).Refresh

    End If

    End Sub

    Unfortunately I am receiving an ‘Subscript out of range (Error 9)’ error.

    Do you have any suggestions what I could change to get this to work?

    Thanks in advance!,

    • Excel Off The Grid says:

      The ‘Subscript out of range (Error 9)’ is because VBA can’t find something that you’ve told it to find. Based on the code, it looks like it cannot find the queries that you’ve named (i.e. the names are wrong, or maybe have a typo)

      I have written the following macro for you which will list the queries in the activeWorkbook. Then you can compare the names you’ve used to ensure they are identical.

      Sub GetConnectionNames()
      Dim obj As Object
      Dim str As String
      For Each obj In ActiveWorkbook.Connections
          If str = "" Then
              str = obj.Name
              str = str & vbNewLine & obj.Name
          End If
      Next obj
      MsgBox str
      Debug.Print str
      End Sub

      Hope that helps.

  5. Kavin says:

    I’m wondering what I’m doing incorrectly. I followed the instructions. When I change the parameter, something does happen, I see a flash of “Calculating ….” in the status bar but nothing happens to the data. I downloaded the example and got the same thing – some calculation is going on but nothing happens to the data, unlike in your clip. Am I missing something or my settings are different?

    • Excel Off The Grid says:

      Hi Kavin – I’ve rechecked the file and it’s still working for me.

      I’m not sure what might cause that, but the things I would check are:
      (a) Are you in manual calculation mode
      (b) Have you enabled the content (clicking the yellow button at the top).
      (c) Are macros enabled

  6. Jeya says:

    When I do a refresh…refreshed cell is automatically highlighted after each refresh and how to disable automatic highlighting of refreshed cell

  7. Dave says:

    I downloaded the file you provided but upon selecting a different name under sold by, the information does not change. That being said, I’m not sure the download works?

Leave a Reply

Your email address will not be published. Required fields are marked *