VBA With Power Query: Maximize Efficiency and Automate Your Data Processes in Excel (with VBA code)

What are the benefits of using VBA with Power Query?

Using VBA in conjunction with Power Query can provide significant benefits, especially when you need to automate complex workflows, integrate data from multiple sources, or perform advanced transformations programmatically. Here are the key benefits of using VBA over just using Power Query directly:

  1. Automation and Repetition:
    • Automation: VBA allows you to automate repetitive tasks, such as importing data from multiple files, applying the same transformations, and saving the results in a consistent format.
    • Scheduling: You can schedule VBA macros to run at specific times, ensuring data is updated automatically.
  2. Customization and Flexibility:
    • Custom Functions: VBA enables you to create custom functions and procedures that can be used within Power Query M code.
    • Dynamic Parameters: You can pass dynamic parameters to Power Query queries using VBA, allowing for more flexible data processing. This alone is a huge benefit!!
  3. Integration with Other Applications:
    • Interoperability: VBA can interact with other applications and services, such as databases, web APIs, and email clients, enhancing the capabilities of Power Query.
    • Data Export: You can use VBA to export data to various formats, such as PDF, CSV, or other Excel files, after it has been processed by Power Query.
  4. Complex Logic and Control:
    • Conditional Logic: VBA provides powerful conditional logic and control structures that can be used to handle complex data processing tasks.
    • Error Handling: You can implement robust error handling in VBA to manage unexpected issues during data processing.
  5. User Interface:
    • Custom UserForms: VBA allows you to create custom user interfaces (UserForms) for data entry and interaction, making it easier for users to perform complex tasks without needing to know Power Query M code.
    • Buttons and Macros: You can add buttons and macros to Excel worksheets to trigger VBA scripts, making it user-friendly.
  6. Advanced Data Manipulation:
    • Data Cleaning: VBA can be used for advanced data cleaning tasks, such as removing specific patterns, handling missing data, and normalizing data formats.
    • Data Transformation: VBA can perform complex transformations that might be difficult or impossible to achieve with Power Query alone.
  7. Version Control and Collaboration:
    • Version Control: VBA code can be version-controlled using tools like Git, allowing for better collaboration and tracking changes.
    • Shared Macros: You can share VBA macros with your team, ensuring consistency in data processing workflows. This can be especially helpful for vacation coverage or spreading the workload among multiple team members!
  8. Performance Optimization:
    • Efficiency: For large datasets, VBA can be more efficient in certain scenarios, especially when combined with Power Query for initial data loading and filtering.
    • Resource Management: VBA can manage system resources more effectively, ensuring smooth performance during data processing.

When to Use VBA Over Power Query

  • Complex Workflows: When you need to perform a series of complex transformations and data manipulations that are difficult to achieve with Power Query alone.
  • Integration with Other Systems: When you need to integrate Excel with other applications, databases, or web services.
  • Automated Reporting: When you need to automate the generation of reports and dashboards based on dynamic data sources.
  • Custom User Interfaces: When you need to create custom user interfaces for data entry and interaction.
  • Advanced Error Handling: When you need robust error handling and logging for data processing tasks.

When to Use Power Query Alone

  • Simple Data Transformation: When you need to perform simple data transformations and cleaning tasks.
  • Data Visualization: When you need to create dynamic data visualizations and dashboards.
  • Data Integration: When you need to integrate and combine data from multiple sources without complex logic.
  • Data Refresh: When you need to refresh data regularly from external sources.
  • Data Transformation: Power Query allows for complex data transformations, such as filtering, merging, and aggregating data.
  • Refreshable Data: Data imported using Power Query can be easily refreshed to update with new data.
  • Scalability: Power Query is better suited for larger datasets and more complex data processing tasks.

VBA with Power Query Code Samples with Explanations

Use Case: Importing Data from CSV Files Using Power Query

Power Query is a more advanced and flexible tool for data import and transformation in Excel. It allows for more complex data transformations and can handle larger datasets more efficiently. Here’s how you can use VBA to import a CSV file using VBA with Power Query.

End Sub

Explanation of Power Query VBA Code

  1. File Path and Connection Name:
    • filePath is the path to your CSV file
    • connName is the name of the Power Query connection.
  2. Delete Existing Connection:
    • The code checks if the connection already exists and deletes it to avoid conflicts.
  3. Create New Power Query Connection:
    • The Queries.Add method creates a new Power Query connection.
    • The Formula parameter specifies the Power Query M code to import and transform the CSV file.
  4. Load Query into Worksheet:
    • A new worksheet is created, and the query is loaded into it using LoadFromText

Use Case: Importing and Transforming Data from an Excel File Using Power Query and VBA

Objective: Import data from a specific worksheet in an Excel file, filter out rows with specific criteria, perform some transformations, and load the cleaned data into a new worksheet.

Preparation:

  1. Prepare the Source Excel File:
    • Ensure your source Excel file is located at a known path, e.g., C:\Data\source_data.xlsx.
    • Ensure the data is in a worksheet named SalesData.
  2. VBA Code to Import and Transform Data Using Power Query:

Explanation of the VBA Code

  1. Set File Path, Workbook Name, Sheet Name, and Names:
    • sourceFilePath is the path to your source Excel file.
    • sourceWorkbookName is the name of the source Excel file.
    • sourceSheetName is the name of the worksheet containing the data.
    • connName is the name of the initial Power Query connection.
    • queryName is the name of the transformed Power Query query.
  2. Delete Existing Connection and Query:
    • The code checks if the connection and query already exist and deletes them to avoid conflicts.
  3. Create a New Power Query Connection:
    • The Queries.Add method creates a new Power Query connection to import data from the specified worksheet in the Excel file.
    • The Formula parameter specifies the Power Query M code to import the data.
  4. Create a New Power Query Query for Transformation:
    • This query uses the initial connection as its source.
    • It skips the first row (assuming headers).
    • It removes duplicates based on specified columns.
    • It filters rows where Sales is greater than 100.
    • It sorts the filtered rows by Date in ascending order.
    • It adds a new column TotalSales calculated as Sales * Quantity.
  5. Load the Transformed Query into a New Worksheet:
    • A new worksheet is created, and the transformed query is loaded into it using LoadFromText.
  6. Format the Worksheet:
    • The code automatically fits the columns and applies a table style for better readability.

Detailed Steps

  1. Prepare the Source Excel File:
    • Update the path to match your source Excel file.
    • Ensure the data is in a worksheet named SalesData, or update that variable to match your data.
  2. Open VBA Editor:
    • Press Alt + F11 to open the VBA editor.
  3. Insert a New Module:
    • In the VBA editor, go to Insert > Module to create a new module.
  4. Copy and Paste the VBA Code:
    • Copy the above VBA code and paste it into the module.
  5. Run the Macro:
    • Close the VBA editor and return to Excel.
    • Press Alt + F8, select ImportAndTransformExcelDataWithPowerQuery, and click Run.
  6. View the Results:
    • A new worksheet named TransformedData will be created, showing the imported and transformed data.

Additional Tips

  • Customizing Columns:
    • You can customize the column names and the criteria for filtering and sorting based on your specific dataset.
  • Handling Different Workbooks and Sheets:
    • Adjust the sourceFilePath, sourceWorkbookName, and sourceSheetName variables to match your source file and worksheet.
  • Error Handling:
    • Add error handling to manage potential issues, such as file not found or invalid data.

Example: Combining VBA with Power Query for Automation of Reporting

Here’s a more detailed example that combines VBA with Power Query to automate a complex data processing workflow that can automate data reporting from start to finish, including transforming the data and outputting a user-friendly report.

Use Case: Automating Data Import, Transformation, and Reporting

Objective: Import data from multiple Excel files, perform transformations, and generate a consolidated report.

VBA Code:

Explanation of the VBA Code

  1. Set Folder Path and Names:
    • folderPath is the path to the folder containing the Excel files.
    • connName is the name of the initial Power Query connection.
    • queryName is the name of the transformed Power Query query.
  2. Delete Existing Connection and Query:
    • The code checks if the connection and query already exist and deletes them to avoid conflicts.
  3. Initialize a New Worksheet:
    • A new worksheet named ConsolidatedData is created to store the consolidated data.
  4. Loop Through Excel Files:
    • The code loops through all Excel files in the specified folder.
    • For each file, it creates a new Power Query connection to import data from the SalesData worksheet.
  5. Create a New Power Query Query for Transformation:
    • This query uses the initial connection as its source.
    • It skips the first row (assuming headers).
    • It removes duplicates based on specified columns.
    • It filters rows where Sales is greater than 100.
    • It sorts the filtered rows by Date in ascending order.
    • It adds a new column TotalSales calculated as Sales * Quantity.
  6. Load the Transformed Query into the Consolidated Worksheet:
    • The transformed data is loaded into the ConsolidatedData worksheet.
  7. Delete the Power Query Connection and Query:
    • After processing each file, the connection and query are deleted to clean up.
  8. Format the Worksheet:
    • The code automatically fits the columns and applies a table style for better readability.

Conclusion

Using VBA in conjunction with Power Query provides a powerful combination for automating and managing complex data workflows. While Power Query is excellent for data transformation and integration, VBA offers the flexibility and control needed for advanced automation and integration tasks. By combining these tools, you can create robust and efficient data processing solutions.

Feel free to comment other examples you would like to see as we continue to explore automation of workflows via both VBA and Power Query!

MS 365 Excel Basics #5: IF Function & Logical Test. IFS, IFNA, OR, AND, NOT, ISNUMBER Functions More

Download Excel File: https://people.highline.edu/mgirvin/AllClasses/218M365/Content/ExcelBasics05.xlsx
Read (download right-click): pdf notes: https://people.highline.edu/mgirvin/AllClasses/218M365/Content/ExcelBasics05.pdf
In this video learn about logical tests which are the driver behind functions like IF, IFS, AND, OR, NOT, ISNUMBER and more. See 14 examples of logical tests and the IF function and more.
Topics:
1. (00:00) Introduction
2. (00:40) Topics in Video
3. (01:19) IF function and its arguments
4. (01:56) Logical tests in the Excel worksheet: Complete Story
5. (08:48) Logical formula using comparative operators, including a comparison to how comparative operators are used in functions like SUMIFS and COUNTIFS
6. (10:45) Logical formula using ISNUMBER function
7. (11:55) Logical formula using Continue reading “MS 365 Excel Basics #5: IF Function & Logical Test. IFS, IFNA, OR, AND, NOT, ISNUMBER Functions More”

Excel – Unlock the Secrets of Excel’s New Compatibility Version! – Episode 2663

Microsoft Excel Tutorial: Unlock the Secrets of Excel’s New Compatibility Version!

Are you tired of mismatched results when sharing Excel files between coworkers using different versions? Microsoft has finally addressed this issue. Today we dive into the game-changing **Function Compatibility Version**.
This feature offers a solution to inconsistencies caused by updates to five key functions: **LEN, MID, SEARCH, FIND, and REPLACE**. While the updates might seem minor, the implications are massive, especially for teams juggling old and new versions of Excel.
Learn how the new **Compatibility Version** setting makes it easier to manage version disparities. Whether you’re stuck on Excel Continue reading “Excel – Unlock the Secrets of Excel’s New Compatibility Version! – Episode 2663”

Excel Assign Thanksgiving Dinner Sides Using Excel – Episode 2662

Microsoft Excel Tutorial: Randomly Assign Sides for Thanksgiving Dinner

In today’s tutorial, we’re tackling a fun holiday challenge: assigning dinner sides for Thanksgiving using Excel! Whether you’re hosting a big feast or coordinating a potluck, Excel makes it easy to assign dishes randomly and fairly. In this video, I’ll walk you through the process step by step, using Excel’s powerful SORTBY and RANDARRAY functions.

Have you ever used a spreadsheet to manage your holiday meals? Let me know in the comments! My friend Katie from my morning workout group inspired this video—she needed a way to assign sides for her Continue reading “Excel Assign Thanksgiving Dinner Sides Using Excel – Episode 2662”

MS 365 Excel Basics #4: Date & Time Formulas, Functions & Formatting: Everything You Need to Know!!

Download Excel File: https://people.highline.edu/mgirvin/AllClasses/218M365/Content/ExcelBasics04.xlsx
Read (download right-click): pdf notes: https://people.highline.edu/mgirvin/AllClasses/218M365/Content/ExcelBasics04.pdf
In this video learn about
Topics:
1. (00:00) Introduction
2. (00:38) How Dates work in Excel (Date Serial Numbers, Date Number Format and Date Formulas)
3. (07:57) Formulas to calculate number of days between two dates, for invoices, loans and projects
4. (10:00) Formulas to count workdays with NETWORKDAYS.INTL function
5. (12:00) Series dialog box to create list of dates
6. (14:40) Add days to date to get future date. Learn about WORKDAY.INTL to find future or past date based on workdays only. Examples such as calculating loan due dates..
7. (16:22) Subtract Continue reading “MS 365 Excel Basics #4: Date & Time Formulas, Functions & Formatting: Everything You Need to Know!!”

MS 365 Excel Basics #3: Number Formatting as Façade & when you MUST use ROUND Function

Download Excel File: https://people.highline.edu/mgirvin/AllClasses/218M365/Content/ExcelBasics03.xlsx
Read (download right-click): pdf notes: https://people.highline.edu/mgirvin/AllClasses/218M365/Content/ExcelBasics03.pdf
In this video learn about how to not be tricked by Number Formatting, and how to use the ROUND function rather than number formatting to calculate accurate payroll, invoicing and income tax calculations. Lean about difference between Currency and Accounting Number Formatting.
Topics:
1. (00:00) Introduction
2. (01:04) What does Number Formatting do?
3. (02:38) Formulas do not see Number Formatting
4. (04:10) Keyboard to apply General Number Formatting (Eraser): Ctrl + Shift + ~ / `
5. (04:40) Number Formatting can save time entering data.
6. (07:40) Currency and Accounting Number Formatting
7. Continue reading “MS 365 Excel Basics #3: Number Formatting as Façade & when you MUST use ROUND Function”

Excel Which Products Contain Both Of These Items – Episode 2661

Microsoft Excel Tutorial: Which Products Contain Both Of These Items?

Today, an odd data problem. I have a solution, but I suspect there are much easier ways to do this. I have a list of songs in workouts from Supernatural VR. Over 500 workouts are Quick Hits with just two songs. Each Quick Hits workout should be a subset of a longer workout. Given the two lists, how can you use Excel to find the parent workout?

My solution involves an XLOOKUP with a concatenated key and a concatenated lookup vector. This gives me a list of the Workout IDs that contain Continue reading “Excel Which Products Contain Both Of These Items – Episode 2661”

MS 365 Excel Basics #2: Add & Count Formulas with COUNT, COUNTA, ROWS, SUM, SUMIFS, COUNTIFS & IF

Download Excel File: https://excelisfun.net/files/ExcelBasics02.xlsx
pdf notes: https://excelisfun.net/files/ExcelBasics02.pdf
In this video learn every trick there is for Excel formula counting and adding with 10 different Excel Built-in Functions, including how to add and count with a single condition, two or more conditions, an AND Logical Test, and even the elusive OR Logical Test. See many use business examples.
This video is taught by Mike “excelisfun” Girvin, Highline College Profession since 2002 years and excelisfun YouTuber since 2008. This video is #2 in a class of 10 free videos and Excel files! This is a free YouTube class that Continue reading “MS 365 Excel Basics #2: Add & Count Formulas with COUNT, COUNTA, ROWS, SUM, SUMIFS, COUNTIFS & IF”

MS 365 Excel Basics #1 What is Excel?, Formulas, Functions, Formatting, Cell References & Page Setup

Download Excel File: https://excelisfun.net/files/ExcelBasics01.xlsx
pdf notes: https://excelisfun.net/files/ExcelBasics01.pdf
In this video learn about the different types of formulas and functions in MS 365 Excel, as well as how to so style and number formatting. Learn about all the shortcuts that will allow you to create an Excel solution with lightening speed and accuracy.
In this video get a complete introduction to Excel basics taught by Mike “excelisfun” Girvin, Highline College Profession since 2002 years and excelisfun YouTuber since 2008. This is video is first in a class of 10 free videos and Excel files!
This is a free YouTube Continue reading “MS 365 Excel Basics #1 What is Excel?, Formulas, Functions, Formatting, Cell References & Page Setup”

Excel Easy Fake Data From Python In Excel – Episode 2660

Microsoft Excel Tutorial: Excel Fake Data From Python In Excel

Creating fake data with Python in Excel has never been easier! In this video, I walk you through generating random data directly in Excel using Python’s powerful capabilities. We start from a completely blank workbook, search for Python, and dive into some exciting new options like the QR code generator and random data generator. This process is amazing for anyone who needs quick, randomized data sets without leaving Excel. Just a few clicks, and you can have it all right at your fingertips!

We’ll start by setting up Python to generate a Continue reading “Excel Easy Fake Data From Python In Excel – Episode 2660”

Excel Draw Perfect Shapes With Draw And Hold Gesture – Episode 2659

Microsoft Excel Tutorial: Draw Perfect Shapes With Draw And Hold Gesture
In this video, I’m diving into a new feature in Microsoft Excel: the Draw and Hold Gesture!
If you’ve ever wanted to create shapes in Excel without struggling with awkward mouse drawing, this update is for you. While the feature has been available in OneNote for a while, it’s finally made its way to Excel and PowerPoint—at least for those on the Insider’s channel. I’ll walk you through how to activate this new tool and show you what it can do!

First, if you don’t see the Draw tab in Continue reading “Excel Draw Perfect Shapes With Draw And Hold Gesture – Episode 2659”

Excel Introduces TRANSLATE and DETECTLANGUAGE Functions – Episode 2645

Microsoft Excel Tutorial: Excel Introduces TRANSLATE and DETECTLANGUAGE Functions.

Unlock the Power of Excel’s New Functions: TRANSLATE and DETECTLANGUAGE

To download the workbook from today: https://www.mrexcel.com/youtube/rOQraANkokQ/

Hey Excel enthusiasts! If you found this video helpful, don’t forget to click Like down below. It helps more people discover this content. In this video, we’re diving into two amazing new Excel functions: TRANSLATE and DETECTLANGUAGE. These functions are game-changers, making it easier than ever to work with different languages in Excel.

First up, the TRANSLATE function. This powerful tool allows you to translate any text from one language to another effortlessly. Just enter Continue reading “Excel Introduces TRANSLATE and DETECTLANGUAGE Functions – Episode 2645”