Merge Multiple Excel Files with Dynamic Header Selection
Build a Flexible, User-Controlled File Consolidation System ā No VBA Required!
šÆ What You’ll Build
Imagine having 50+ Excel files in a folder ā all with similar structures but you only need specific columns. Manually copying and pasting? That’s hours of tedious work and a recipe for errors.
In this guide, you’ll create a dynamic Power Query solution that:
š How It Works ā The Big Picture
tblSourcePath
TblHeaders
Merge Engine
Clean Data
The magic happens through two Excel tables that control your query:
| Table Name | Purpose | What You Define |
|---|---|---|
tblSourcePath |
Tells Power Query WHERE to look | Folder path containing your Excel files |
TblHeaders |
Tells Power Query WHAT columns to extract | Column names + TRUE/FALSE checkbox |
š ļø Step 1: Create the Control Tables
Table 1: Source Path (tblSourcePath)
Create a single-column table with your folder path:
| FolderPath |
|---|
| C:\Reports\MonthlyData\ |
Important
Include the trailing backslash \ at the end of the folder path. Select the cell, go to Insert ā Table, and name it tblSourcePath in the Table Design tab.
Table 2: Header Selection (TblHeaders)
Create a two-column table listing ALL possible headers from your source files:
| Header | Include |
|---|---|
| Invoice Number | TRUE |
| Customer Name | TRUE |
| Amount | TRUE |
| Internal Notes | FALSE |
| Created By | FALSE |
Include column. This gives you a clean TRUE/FALSE selector instead of manual typing.
š Step 2: The Header Filter Query
This query reads your TblHeaders table and extracts ONLY the column names marked as TRUE. It returns a list that the main query will use.
š What Each Step Does
Excel.CurrentWorkbook()
Connects to a named table in the current workbook. The {[Name="TblHeaders"]} syntax finds the specific table.
Table.TransformColumnTypes()
Ensures “Header” is text and “Include” is a logical (TRUE/FALSE) value. This prevents type mismatch errors.
Table.SelectRows()
Filters the table to keep only rows where Include = true. This is your checkbox logic!
Table.SelectColumns()
Removes the “Include” column ā we only need the header names now.
[Header] ā List Extraction
Converts the single-column table to a List. This is crucial ā the main query needs a list, not a table.
ā” Step 3: The Main File Merge Query
This is the powerhouse query that scans your folder, opens each Excel file, and extracts only the selected columns.
š¬ Deep Dive: Key Concepts Explained
š Folder.Files() ā The Folder Scanner
This function returns a table with ALL files in the specified folder. Each row contains binary content (Content) and metadata like filename, extension, and path.
š Excel.Workbook() ā The File Opener
Converts binary content into a readable Excel workbook structure. The true parameter tells Power Query to use the first row as headers.
š Table.ExpandTableColumn() ā The Magic Expander
This is where the dynamic header selection happens. Instead of hardcoding column names, we pass the TblHeaders list:
TblHeaders isn’t a static list ā it’s a reference to another query. Every time you refresh, Power Query re-evaluates TblHeaders, reads your current TRUE/FALSE selections, and expands only those columns. Pure elegance!
š« Filtering Temporary Files
Excel creates temporary files (starting with ~) when workbooks are open. This line prevents errors:
š Copy-Paste Ready Queries
Here are both queries ready to copy. Follow the naming guide below carefully ā the names must match exactly for the queries to connect!
Query 1: TblHeaders
Query Name: TblHeaders (must be exactly this name)
let Source = Excel.CurrentWorkbook(){[Name="TblHeaders"]}[Content], #"Changed Type" = Table.TransformColumnTypes(Source,{{"Header", type text}, {"Include", type logical}}), #"Filtered Rows" = Table.SelectRows(#"Changed Type", each ([Include] = true)), #"Removed Other Columns" = Table.SelectColumns(#"Filtered Rows",{"Header"}), Header = #"Removed Other Columns"[Header] in Header
Query 2: MergedData (Main Query)
Query Name: MergedData (or any name you prefer)
let SourceFolder = Excel.CurrentWorkbook(){[Name="tblSourcePath"]}[Content], Custom1 = SourceFolder[FolderPath]{0}, Source = Folder.Files(Custom1), #"Removed Other Columns" = Table.SelectColumns(Source,{"Content", "Name"}), #"Renamed Columns" = Table.RenameColumns(#"Removed Other Columns",{{"Name", "FileName"}}), ToWorkbook = Table.TransformColumns( #"Renamed Columns", {{"Content", each Excel.Workbook(_, true), type table}} ), #"Expanded Content" = Table.ExpandTableColumn(ToWorkbook, "Content", {"Name", "Data", "Item", "Kind", "Hidden"}, {"Name", "Data", "Item", "Kind", "Hidden"}), #"Filtered Rows" = Table.SelectRows(#"Expanded Content", each [Kind] = "Sheet"), #"Filtered Rows1" = Table.SelectRows(#"Filtered Rows", each not Text.StartsWith([FileName], "~")), #"Removed Columns" = Table.RemoveColumns(#"Filtered Rows1",{"Name", "Item", "Kind", "Hidden"}), #"Expanded Data" = Table.ExpandTableColumn(#"Removed Columns", "Data", TblHeaders, TblHeaders) in #"Expanded Data"
š Critical: How Names Connect Everything
The magic of this solution depends on exact name matching between your Excel tables and Power Query references. Here’s the complete map:
| Excel Table Name | Referenced In Query | What It Controls |
|---|---|---|
tblSourcePath |
Excel.CurrentWorkbook(){[Name="tblSourcePath"]} |
Folder location of your Excel files |
TblHeaders |
Excel.CurrentWorkbook(){[Name="TblHeaders"]} |
List of column headers with TRUE/FALSE |
| ā Query-to-Query Connection ā | ||
TblHeaders (Query) |
Table.ExpandTableColumn(..., TblHeaders, TblHeaders) |
Passes the filtered header list to main query |
tblheaders (lowercase) but the query says "TblHeaders", it will fail! Power Query table names are case-sensitive.
š Complete Implementation Guide
Phase 1: Create Excel Tables (5 minutes)
Create the Source Path Table
In a new worksheet, type your folder path in cell A1 with header “FolderPath” above it:
| A |
|---|
| FolderPath |
| C:\MyReports\SalesData\ |
Convert to Table & Name It
Select cells A1:A2 ā Press Ctrl + T ā Check “My table has headers” ā Click OK
Name the Table Exactly
With table selected, go to Table Design tab ā In the Table Name box (top-left), type: tblSourcePath
Create the Headers Table
In another area or worksheet, create this structure:
| Header | Include |
|---|---|
| Invoice No | TRUE |
| Customer | TRUE |
| Amount | TRUE |
| Notes | FALSE |
| Created By | FALSE |
Convert & Name as TblHeaders
Select all data including headers ā Ctrl + T ā Name the table: TblHeaders
TRUE,FALSE. Now you get a clean dropdown!
Phase 2: Create Power Queries (5 minutes)
Open Power Query Editor
Go to Data tab ā Get Data ā Launch Power Query Editor
Create First Query (TblHeaders)
Home ā New Source ā Other Sources ā Blank Query
Open Advanced Editor
Click Advanced Editor in the Home tab ā Delete all existing code ā Paste Query 1: TblHeaders code from above
Name the Query (CRITICAL!)
In the right panel under Query Settings ā Name, type exactly: TblHeaders
Create Second Query (MergedData)
Repeat: New Source ā Blank Query ā Advanced Editor ā Paste Query 2: MergedData code ā Name it MergedData
Load to Excel
Select MergedData query ā Home ā Close & Load ā Your merged data appears in a new worksheet!
ā Pre-Flight Checklist
Before clicking “Close & Load”, verify these items:
| ā | Item | How to Verify |
|---|---|---|
| ā | Excel table named tblSourcePath |
Click table ā Check Table Design tab ā Table Name box |
| ā | Excel table named TblHeaders |
Click table ā Check Table Design tab ā Table Name box |
| ā | Folder path ends with backslash \ |
Check tblSourcePath ā Should be C:\Folder\ not C:\Folder |
| ā | At least one header marked TRUE | Check TblHeaders ā Include column has at least one TRUE |
| ā | Query named exactly TblHeaders |
Power Query Editor ā Right panel ā Query Settings ā Name |
| ā | Header names match source files exactly | Open one source file ā Compare column names with TblHeaders table |
| ā | Source files are closed | Close all Excel files in the source folder before refreshing |
š¼ Real-World Use Cases
| Industry | Scenario | Benefit |
|---|---|---|
| Internal Audit | Merge 100+ branch audit reports | Extract only Observation, Risk Rating, Status ā skip internal notes |
| Finance | Consolidate monthly P&L from subsidiaries | Select Revenue, Expenses, Net Profit ā exclude draft columns |
| HR | Combine employee data from regional offices | Import Name, Department, Salary ā skip sensitive personal info |
| Sales | Merge weekly sales reports | Get Product, Quantity, Revenue ā exclude rep commission details |
š” Pro Tips & Best Practices
TblHeaders exactly match the column headers in your source files ā including spaces and capitalization!
Folder.Files() with Folder.Files(FolderPath, [Recursive=true]).
š Master Power Query with DAXified
Join our community for more Excel automation tutorials, Power BI guides, and real-world solutions.
ā¶ļø Watch Video Tutorials š¬ Join WhatsApp Communityš Wrapping Up
You’ve just built a production-ready file consolidation system that would take hours to replicate manually. The beauty of this approach is its flexibility ā change your header selections anytime, drop new files in the folder, and hit Refresh. Power Query handles the rest.
This pattern ā using Excel tables to control Power Query behavior ā is a game-changer for building user-friendly, maintainable solutions. No VBA, no complex formulas, just clean M code doing the heavy lifting.
