Sub topic 19
Using parameters to make queries reusable
This chapter assumes you can build queries in the Power Query Editor, read basic M code in the formula bar, and combine files from a folder (covered in earlier chapters). You should also know that each query is a named step list that you can reference from other queries.
What a parameter is
A parameter is a named, single value that other queries can read. Instead of typing C:\Data\sales.csv inside a query, you store the path in a parameter called FilePath and refer to it by name. To point the query at a new file, you change one value, not edit M code.
Parameters help in three common situations:
- A folder or file path differs between machines or users.
- A filter value, such as a year or a region, changes often.
- Several queries must share the same setting, so you want to change it in one place.
Under the hood, a parameter is a query whose result is a value (text, number, date, and so on) instead of a table. It carries extra metadata that tells the editor to treat it as a parameter.
Creating a parameter in the editor
- In the Power Query Editor, choose Home > Manage Parameters > New Parameter.
- Enter a Name with no spaces, such as
FolderPath. The name is how M code refers to it. - Choose a Type: Text, Decimal Number, Date, True/False, and so on.
- Choose Suggested Values: Any value, List of values, or Query.
- Enter the Current Value and select OK.
The parameter appears in the Queries pane with a special icon. Its current value is the one every dependent query uses on the next refresh.
Required and optional
The Required box matters. If it is checked, the current value cannot be empty. If you leave it unchecked, the value may be null, and any step that uses it must cope with null.
Suggested values
| Option | Behavior | Use it when |
|---|---|---|
| Any value | You type any value of the chosen type | The value is open-ended, such as a path |
| List of values | You enter a fixed list and pick a default | Only a few choices are valid, such as `North`, `South`, `East` |
| Query | Choices come from a list query | The valid values live in your data |
A "Query" option needs a query that returns a list, not a table. To turn a table column into a list, right-click the column header and choose Drill Down, or write Regions[Region] in M.
Using a parameter in a query
Open the query you want to change. In the formula bar or Advanced Editor, replace the literal value with the parameter name. A parameter is not quoted, because it is an identifier.
The following query reads a CSV from a path stored in FilePath and keeps only rows for one region stored in RegionFilter:
let
Source = Csv.Document(File.Contents(FilePath), [Delimiter=",", Encoding=65001, QuoteStyle=QuoteStyle.Csv]),
Promoted = Table.PromoteHeaders(Source, [PromoteAllScalars=true]),
Typed = Table.TransformColumnTypes(Promoted, {{"OrderID", Int64.Type}, {"Amount", type number}}),
Filtered = Table.SelectRows(Typed, each [Region] = RegionFilter)
in
FilteredFor this to run, FilePath and RegionFilter must exist as parameters (both of type Text). If you mistype a name, you get an error such as The name 'FilePth' wasn't recognized. M is case-sensitive, so filepath and FilePath are different names.
Using the filter dialog
You do not have to write the filter by hand. Filter the column to any value, then edit the formula bar and replace the typed text in quotes with the parameter name. Power Query then treats it as an expression and no longer shows the value in the filter dropdown as a fixed choice.
Changing a parameter value
You can change a value in two places:
- In the editor, select the parameter in the Queries pane and edit Current Value in the main area.
- In the workbook, right-click the query in the Queries & Connections pane and choose Edit, then change it in the editor. Excel has no built-in cell for parameters.
After you change a value, refresh the queries that depend on it. The new value flows through every step that uses it.
Driving a parameter from a worksheet cell
Excel does not offer a parameter dialog for end users, so a common pattern is to store the value in a one-cell Excel table and load it as a query. Say you create a table named Settings with columns Name and Value, and a row where Name is Region.
Create a query for the table, then a second query that extracts one value:
let
Source = Excel.CurrentWorkbook(){[Name="Settings"]}[Content],
Row = Table.SelectRows(Source, each [Name] = "Region"),
RegionValue = Row{0}[Value]
in
RegionValueName this query RegionFilter. It returns a single text value, so other queries can use it exactly as they would a parameter. Users now change the value in the worksheet and press Data > Refresh All.
Gotchas with this pattern
- If no row matches,
Row{0}raises an error because the table is empty. Guard it withRow{0}?[Value], which returns null instead. - Set the data type of the
Valuecolumn before you read it, or you may get text where you expected a number or date. A column holding mixed types is typed as text, which can break comparisons. - Load the
Settingsquery as Only Create Connection if you do not need to see the value in a sheet. - Query dependencies must not form a cycle. A query that reads a table it also writes to will fail.
Parameters and combining folder files
In the folder-combine chapter you built a query that reads every file in a folder. Its first step has the path typed in:
let
Source = Folder.Files("C:\Data\Monthly"),
CsvOnly = Table.SelectRows(Source, each Text.EndsWith([Extension], ".csv", Comparer.OrdinalIgnoreCase))
in
CsvOnlyReplace the path with a FolderPath parameter:
let
Source = Folder.Files(FolderPath),
CsvOnly = Table.SelectRows(Source, each Text.EndsWith([Extension], ".csv", Comparer.OrdinalIgnoreCase))
in
CsvOnlyWhen you use Combine & Transform on a folder, Power Query already generates helper objects, including a parameter named Parameter1 and a sample-file query. If you rename Parameter1 to something clear, update the dependent queries too. The editor does this automatically when you rename through the Queries pane.
Reusable queries as functions
A parameter holds one value for the whole workbook. If you need to run the same logic for many inputs, such as one query run for each file or year, turn the query into a function. A function declares its inputs and returns a result for each call.
let
LoadYear = (Year as number) as table =>
let
Path = "C:\Data\Sales" & Number.ToText(Year) & ".csv",
Source = Csv.Document(File.Contents(Path), [Delimiter=",", Encoding=65001, QuoteStyle=QuoteStyle.Csv]),
Promoted = Table.PromoteHeaders(Source, [PromoteAllScalars=true])
in
Promoted
in
LoadYearSave this as a query named LoadYear. To call it, add a custom column that holds LoadYear([Year]) for a table of years, then expand the result. You can also right-click a query in the Queries pane and choose Create Function, which converts the query's parameters into function arguments.
The following diagram shows how parameters and a function feed queries.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Expression.Error: The name 'X' wasn't recognized` | Typo, wrong case, or the parameter was deleted | Check the name in the Queries pane |
| `DataSource.Error: Could not find file` | Path value is wrong or the file moved | Correct the current value |
| Data privacy prompt after using a parameter | Combining data from different sources in one step | Set privacy levels, or restructure so sources are read in separate queries |
| Filter returns no rows | Type mismatch, such as a number compared to text | Make the parameter type match the column type |
| Value resets after reopening | You edited a query's step, not the parameter | Edit the parameter itself |
Summary of decisions
- Use a parameter for a single value that you change from the editor.
- Use a settings table when people who never open the editor need to change the value.
- Use a function when the same logic must run for many inputs.
- Keep names short and consistent, such as
FolderPathandRegionFilter, so M code stays readable.
Exercise
Your query reads Folder.Files("C:\Data\Monthly"). A colleague stores their files in D:\Reports\Monthly. Describe how to make the same workbook work for both of you without editing M code each time, and name one risk of the approach.
Show answer
Create a Text parameter named FolderPath with the current value set to the colleague's or your own folder. Change the first step to Folder.Files(FolderPath). Each person sets the current value to their own path and refreshes. A risk is that the stored path travels with the workbook, so a recipient may see a path that does not exist on their machine and get a "Could not find" error until they update it. Another acceptable risk is exposing a local user name in the path.
Exercise
A settings table query uses Row{0}[Value] and the refresh fails with an error after someone deletes the "Region" row. What change makes the query return null instead, and what should the downstream filter do with null?
Show answer
Change the expression to Row{0}?[Value], which returns null when the row does not exist. The downstream filter should handle null explicitly, for example by skipping the filter when RegionFilter is null: each RegionFilter = null or [Region] = RegionFilter.