How To Split Columns By Delimiters In Power BI Using DAX

Data preparation is a crucial step in any Power BI project, and one of the most common challenges is dealing with columns that contain multiple values separated by delimiters. Whether you’re working with comma-separated names, pipe-separated categories, or any other delimiter-based data, knowing how to split columns using DAX can save you significant time and effort.

Understanding Column Splitting in Power BI

When working with data in Power BI, you’ll often encounter columns that contain multiple pieces of information separated by specific characters (delimiters). Common examples include:

  • Full names separated by spaces: “John Smith”
  • Email addresses with domains: “[email protected]
  • Product categories separated by commas: “Electronics,Laptops,Gaming”
  • Geographic data with pipes: “USA|California|Los Angeles”

While Power Query provides excellent tools for splitting columns during data transformation, there are scenarios where you need to split columns dynamically using DAX calculations.

When to Use DAX vs Power Query for Column Splitting

Use Power Query When:

  • You need to split columns permanently during data load
  • The split logic is straightforward and won’t change
  • You want to minimize model size and improve performance

Use DAX When:

  • You need dynamic splitting based on user selections
  • The splitting logic needs to be conditional
  • You want to maintain the original column while creating split versions
  • You’re working with calculated columns or measures

Basic DAX Functions for Column Splitting

Key DAX Functions

Before diving into examples, let’s understand the essential DAX functions for string manipulation:

  • LEFT(): Extracts characters from the left side of a string
  • RIGHT(): Extracts characters from the right side of a string
  • MID(): Extracts characters from the middle of a string
  • FIND(): Locates the position of a substring within a string
  • SUBSTITUTE(): Replaces specific text within a string
  • LEN(): Returns the length of a string

Method 1: Splitting Two-Part Strings

Let’s start with the most common scenario – splitting a full name into first and last names.

Example: Splitting Full Names

// Extract First Name
First Name = 
LEFT(
    Table[Full Name], 
    FIND(" ", Table[Full Name]) - 1
)

// Extract Last Name  
Last Name = 
RIGHT(
    Table[Full Name], 
    LEN(Table[Full Name]) - FIND(" ", Table[Full Name])
)

Handling Cases with No Delimiter

To make your DAX more robust, handle cases where the delimiter might not exist:

// Safe First Name extraction
First Name = 
IF(
    ISERROR(FIND(" ", Table[Full Name])),
    Table[Full Name],
    LEFT(Table[Full Name], FIND(" ", Table[Full Name]) - 1)
)

// Safe Last Name extraction
Last Name = 
IF(
    ISERROR(FIND(" ", Table[Full Name])),
    "",
    RIGHT(Table[Full Name], LEN(Table[Full Name]) - FIND(" ", Table[Full Name]))
)

Method 2: Splitting Multi-Part Strings

For columns with multiple delimiters, you’ll need more sophisticated DAX formulas.

Example: Extracting Email Components

// Extract Username from Email
Username = 
LEFT(
    Table[Email], 
    FIND("@", Table[Email]) - 1
)

// Extract Domain from Email
Domain = 
RIGHT(
    Table[Email], 
    LEN(Table[Email]) - FIND("@", Table[Email])
)

// Extract Domain Name (without extension)
Domain Name = 
VAR DomainPart = RIGHT(Table[Email], LEN(Table[Email]) - FIND("@", Table[Email]))
VAR DotPosition = FIND(".", DomainPart)
RETURN
    IF(
        ISERROR(DotPosition),
        DomainPart,
        LEFT(DomainPart, DotPosition - 1)
    )

Method 3: Advanced Splitting with Multiple Delimiters

For complex scenarios with multiple different delimiters, you can use SUBSTITUTE to standardize delimiters first:

// Standardize delimiters and extract first part
First Part = 
VAR StandardizedString = SUBSTITUTE(SUBSTITUTE(Table[Mixed Delimiters], "|", ","), ";", ",")
VAR FirstCommaPosition = FIND(",", StandardizedString)
RETURN
    IF(
        ISERROR(FirstCommaPosition),
        StandardizedString,
        LEFT(StandardizedString, FirstCommaPosition - 1)
    )

Method 4: Creating a Generic Split Function

For repeated use, create a more generic approach:

// Generic function to get the Nth element from a delimited string
Nth Element = 
VAR DelimitedString = Table[Categories]
VAR Delimiter = ","
VAR Position = 2  // Get the 2nd element
VAR AddDelimiter = Delimiter & DelimitedString & Delimiter
VAR StringLength = LEN(AddDelimiter)
VAR FirstOccurrence = FIND(Delimiter, AddDelimiter)
VAR SecondOccurrence = FIND(Delimiter, AddDelimiter, FirstOccurrence + 1)
VAR Result = 
    IF(
        Position = 1,
        MID(AddDelimiter, FirstOccurrence + 1, SecondOccurrence - FirstOccurrence - 1),
        // Add logic for other positions as needed
        ""
    )
RETURN Result

Method 5: Dynamic Column Splitting with Measures

Sometimes you need to split columns dynamically based on user selections:

Dynamic Split Result = 
VAR SelectedSplitType = SELECTEDVALUE(SplitOptions[Split Type])
VAR SourceColumn = SELECTEDVALUE(Table[Source Column])
RETURN
    SWITCH(
        SelectedSplitType,
        "First Name", LEFT(SourceColumn, FIND(" ", SourceColumn) - 1),
        "Last Name", RIGHT(SourceColumn, LEN(SourceColumn) - FIND(" ", SourceColumn)),
        "Domain", RIGHT(SourceColumn, LEN(SourceColumn) - FIND("@", SourceColumn)),
        "No Selection"
    )

Best Practices for Column Splitting with DAX

1. Error Handling

Always include error handling to prevent your reports from breaking:

Safe Split = 
VAR SplitResult = 
    IF(
        ISERROR(FIND(",", Table[Data])),
        Table[Data],
        LEFT(Table[Data], FIND(",", Table[Data]) - 1)
    )
RETURN
    IF(ISBLANK(SplitResult), "", SplitResult)

2. Performance Considerations

  • Use calculated columns for static splits that won’t change
  • Consider using measures for dynamic splits that depend on user interaction
  • Pre-process complex splits in Power Query when possible

3. Data Quality Checks

Implement validation to ensure your splits are working correctly:

Split Validation = 
VAR OriginalLength = LEN(Table[Original Column])
VAR SplitLength = LEN(Table[Part 1]) + LEN(Table[Part 2]) + 1  // +1 for delimiter
RETURN
    IF(OriginalLength = SplitLength, "Valid", "Check Required")

Common Use Cases and Solutions

1. Geographic Data Splitting

Country = LEFT(Table1[Location], FIND("|", Table1[Location]) - 1)
State = MID(Table1[Location], FIND("|", Table1[Location]) + 1, FIND("|", Table1[Location], FIND("|", Table1[Location]) + 1) - FIND("|", Table1[Location]) - 1)

2. Product Code Parsing

Product Category = LEFT(Table1[Product Code], 3)
Product ID = RIGHT(Table1[Product Code], LEN(Table1[Product Code]) - 4)

3. Date and Time Separation

Date Part = LEFT(Table1[DateTime], FIND(" ", Table1[DateTime]) - 1)
Time Part = RIGHT(Table1[DateTime], LEN(Table1[DateTime]) - FIND(" ", Table1[DateTime]))

Troubleshooting Common Issues

Issue 1: “A function ‘FIND’ has been used in a True/False expression”

Solution: Wrap FIND functions in ISERROR() when using in IF statements.

Issue 2: Blank Results

Solution: Check for empty strings and handle them explicitly:

Result = 
IF(
    OR(ISBLANK(Table1[SourceCol]), Table1[SourceCol] = ""),
    "",
    // Your split logic here
)

Issue 3: Performance Problems

Solution: Consider moving complex splitting logic to Power Query or use variables to avoid repeated calculations.

Conclusion

You’ve now learned how to split columns by delimiters in Power BI using DAX! This a powerful technique that provides flexibility for dynamic data manipulation. While Power Query remains the preferred method for static transformations, DAX splitting becomes invaluable when you need conditional logic, user-driven splits, or when working with calculated columns and measures.

Remember to always include proper error handling, test your formulas with various data scenarios, and consider performance implications when choosing between DAX and Power Query approaches. With these techniques and best practices, you’ll be able to handle even the most complex column splitting requirements in your Power BI reports.

Start with simple two-part splits and gradually work your way up to more complex scenarios. The key is understanding how the basic string functions work together and building robust formulas that can handle edge cases in your data.

Keywords: How To Split Columns By Delimiters In Power BI Using DAX

power bi cross selling matrix for retail

Market Basket Analysis in Power BI Cross Selling Matrix For Retail

A cross selling matrix in Power BI is a vital tool for the retail industry, enabling you to visualize and analyze which products are frequently purchased together by the same customers. This type of analysis—also known as market basket analysis—delivers powerful insights that can guide promotions, product placements, and inventory decisions.

Building a Retail Cross Selling Matrix in Power BI

A cross selling matrix helps retailers answer a simple but valuable question: “If a customer buys Product A, how likely are they to also purchase Product B during the same period?” Understanding these patterns allows stores to design smarter upselling strategies and create effective bundles that boost both sales and customer satisfaction.

How It Works

At its core, a cross selling matrix works by tracking customer purchase data to find common purchase combinations. You’ll essentially compare all pairs of products to count the number of unique customers who bought both products in a selected time frame.

Step-by-Step Approach

  1. Prepare the Data Model
  • Ensure you have sales transactions that include at least a product identifier and a customer identifier.
  • Build a product list (dimension) table and a separate transactions (fact) table in your model.
  1. Generate Customer Lists for Each Product
  • For any product, use DAX to create a list (virtual table) of customers who bought it.
  • Do the same for each comparison product in the matrix—these are your “row” and “column” products.
  1. Find Overlaps Using DAX Table Functions
  • Use DAX functions like VALUES() to pull the relevant customer lists.
  • Compare the two lists for every product pair using the INTERSECT() function to find customers who purchased both.
  • The count of intersecting customers is used to populate each matrix cell.
  1. Virtual Relationships for Comparison
  • If your comparison product table isn’t physically connected to the sales table, use TREATAS() within CALCULATETABLE() in DAX to virtually relate them during the comparison.
  • Remove existing context with ALL() where necessary to correctly isolate each calculation.
  1. Dynamic Filtering
  • The matrix remains interactive—choosing different dates or store locations will update results in real time.
  • This adaptability is powerful for seasonality and promotional period analysis.

Example DAX Snippet

Both Products Purchased = 
VAR CustomersProductA = VALUES(Sales[CustomerID])
VAR CustomersProductB = 
    CALCULATETABLE(
        VALUES(Sales[CustomerID]), 
        TREATAS(VALUES(CompareProducts[ProductID]), Sales[ProductID])
    )
RETURN
    COUNTROWS(INTERSECT(CustomersProductA, CustomersProductB))

Adjust table and column names to match your model.

power bi cross selling matrix for retail

Why Retailers Should Use a Power BI Cross Selling Matrix for Retail

  • Optimize Product Placement: Place complementary products near each other to encourage higher basket values.
  • Design Targeted Promotions: Offer discounts or bundles based on frequent purchase pairs.
  • Improve Inventory Management: Stock popular product pairings together to meet customer demand.
  • Enhance Customer Experience: Personalize recommendations for shoppers by suggesting common cross-sells.

Harnessing this approach will empower your retail business to make data-driven merchandising decisions, resulting in increased sales and improved customer loyalty. With a few dynamic DAX formulas and the robust visualization capabilities of Power BI, any retailer can unlock the value hidden in their sales data.

keywords: Power BI Cross Selling Matrix for Retail, Market Basket Analysis in Power BI

lookup last invoice date

Lookup Last Payment Date in Excel: Master Five Solutions for Any Version

When managing invoices and payments, one powerful Excel technique is to quickly lookup the last payment date for each invoice. Whether reconciling accounts or tracking customer payments, knowing the latest payment date is crucial. This tutorial explains five robust ways to achieve an Excel lookup last payment date for any Excel version—from legacy releases to Microsoft 365—so you can use the best method for your workflow.

Lookup Last Payment Date – Why This Functionality Works Well in Excel

Finance teams, small businesses, and freelancers often need a dynamic way to find the most recent payment date by invoice or customer. Manual solutions are slow and error-prone, but Excel’s built-in and advanced formulas let you automate the process reliably.

Method 1: MAXIFS Function (Excel 2016+)

The MAXIFS function delivers the maximum date that matches a given criterion, making it perfect for this lookup scenario1.

How to use:

  • Max Range: The date column.
  • Criteria Range: The invoice column.
  • Criteria: The specific invoice number.

Example:

text=MAXIFS(DateColumn, InvoiceColumn, InvoiceCell)
  • This formula scans all dates and returns the latest date for the matching invoice.

Tip: Use absolute references for the ranges and a relative reference for the criteria to fill the formula down your list efficiently.

Method 2: MAXIFS Spilled Array Solution (Excel 365)

If you have Excel 365 and want to lookup multiple invoices, you can leverage spilled array formulas for a one-formula-down-the-column approach. This is a very flexible solution because the both the lookup list and the invoice data can grow and you never have to update the formula (if it is setup dynamically).

How to use:

=MAXIFS(DateColumn, InvoiceColumn, InvoiceList)
  • The formula outputs the last payment date for every unique invoice in InvoiceList.
  • No manual copying or dragging needed—just one formula that updates dynamically.

Method 3: Excel Table + Dynamic Formulas

Lookup Last Payment Date

Convert your data to an Excel Table (Ctrl+T), name it (e.g., “PaymentTbl”), and use structured references. This is my most preferred method of handling any data in any scenario where it’s possible.

Advantages:

  • Automatically updates when new payments or invoices are added.
  • Combine with spilled array or lookup formulas for continuous reporting.
  • Creates and anchor point – you can easily reference the table columns and data by name from anywhere in your workbook (or even other workbooks).

Method 4: PivotTable (Any Excel Version)

Lookup Last Payment Date PivotT
able

For a no-formula, robust solution, create a PivotTable:

  • Place Dates and in Rows and order the dates descending.
  • You could also place Invoice in Rows, Date in Values (set to Max).
  • Instantly shows the latest payment per invoice.
  • Refresh when new data is added1.

Alternate Method for Older Excel Versions: AGGREGATE Function (Excel 2010+)

If for some reason your version doesn’t have MAXIFS, AGGREGATE is an excellent alternative with built-in LARGE and MAX options plus error handling1.

How to use:

=AGGREGATE(14, 6, DateColumn / (InvoiceColumn = InvoiceCell), 1)
  • Function 14 is LARGE; option 6 ignores errors.
  • This formula divides date values by a logical test, producing errors for non-matches (which are ignored).
  • Returns the largest (latest) date matching the invoice.

Key Takeaways: Excel Lookup Last Payment Date

  • MAXIFS is fastest for Excel 2016/Office 365 and newer.
  • AGGREGATE works well for older Excel versions and advanced users.
  • Spilled arrays (Excel 365) allow a single formula for all invoices.
  • Tables make reporting dynamic as your list grows.
  • Pivot Tables offer a no-code, universal alternative.

Each method lets you efficiently solve “how to lookup last payment date in Excel” with the right formula for your version and skills.

Ready to streamline your financial reporting? Try these techniques to automate your workflow and never miss another last payment date in Excel!

keywords: excel lookup last payment date, find last payment date in Excel, lookup last date by invoice Excel, Excel formula latest payment date, payment lookup solutions.

extract linked workbook

How to Extract Linked Workbook Info from a Formula and Add Hyperlinks Automatically Using VBA in Excel

If you work extensively with Excel, you’ve likely faced formulas that link to external workbooks. Managing and understanding these links can be tricky, especially when you need to extract the workbook’s name or path and create easy navigation through hyperlinks.

In this blog post, you’ll learn how to use a simple yet powerful VBA macro to automatically extract linked workbook information from a formula and add a clickable hyperlink to it. This method streamlines workbook management and enhances spreadsheet navigation. You can quickly see what workbook is being referenced, and if you need to, you can quickly click the link to open it up. No need to go into the Workbook Links panel and click around, which can be challenging if you have several links.

Why Extract Linked Workbook Info and Create Hyperlinks?

Excel formulas that reference external workbooks usually contain the linked workbook’s path and filename in the formula text, like:

text='C:\Users\UserName\Documents\[SalesData.xlsx]Sheet1'!A1

Manually parsing these formulas to find the linked workbook name and create hyperlinks can be tedious. Automating this process helps:

  • Quickly identify all linked files
  • Avoid broken or outdated links
  • Improve navigation within your workbook
  • Save time in auditing external references
extract linked workbook

Here’s the VBA code we’ll use to extract the linked workbook name from a formula in cell A1, store that info in cell B1, and create a clickable hyperlink in cell C1:

Dim wbName As String
Dim cellFormula As Range

Set cellFormula = ws.Range("A1")
fText = cellFormula.Formula

startPos = InStr(fText, "[")
endPos = InStr(fText, "]")

If startPos > 1 Then
filePath = Mid(fText, 2, startPos - 2)
filePath = Replace(filePath, "'", "") ' remove single quotes

wbName = Mid(fText, startPos + 1, endPos - startPos - 1)
wbName = Replace(wbName, "[", "")
wbName = Replace(wbName, "]", "")

Debug.Print filePath & wbName
ws.Range("B1").Value = filePath & wbName
ws.Hyperlinks.Add Anchor:=ws.Range("C1"), _
Address:=filePath & wbName, _
TextToDisplay:=wbName
End If

Breaking Down the Code Step-by-Step

1. Define the Target Cell and Get the Formula

textSet cellFormula = ws.Range("A1")
fText = cellFormula.Formula
  • We focus on cell A1 in the worksheet ws.
  • We grab the entire formula from this cell as a string for processing.

2. Locate the Workbook Name within the Formula

textstartPos = InStr(fText, "[")
endPos = InStr(fText, "]")
  • The workbook name is enclosed in square brackets [WorkbookName.xlsx].
  • InStr finds the position of these brackets in the formula text.

3. Extract the File Path

textfilePath = Mid(fText, 2, startPos - 2)
filePath = Replace(filePath, "'", "")
  • Extract the file path, which usually precedes the [.
  • Remove any single quotes to keep the path clean.

4. Extract and Clean the Workbook Name

textwbName = Mid(fText, startPos + 1, endPos - startPos - 1)
wbName = Replace(wbName, "[", "")
wbName = Replace(wbName, "]", "")
  • Extract the workbook name between the brackets.
  • Remove any remaining brackets for a clean filename.

5. Output the Combined Path and Workbook Name

textDebug.Print filePath & wbName
ws.Range("B1").Value = filePath & wbName
  • Print the full file path combined with the workbook name in the Immediate Window (useful for debugging).
  • Also store this combined string in cell B1.

6. Create a Hyperlink to the Workbook

textws.Hyperlinks.Add Anchor:=ws.Range("C1"), _
    Address:=filePath & wbName, _
    TextToDisplay:=wbName
  • Add a hyperlink in cell C1.
  • The link points to the extracted full path of the linked workbook.
  • The link text displays the workbook name for clarity.

How to Use This VBA Macro in Your Workbook

  1. Open the Visual Basic for Applications editor (Press Alt + F11 in Excel).
  2. Insert a new module: Right-click your workbook in the Project explorer, select Insert > Module.
  3. Copy and paste the code inside a Sub procedure, making sure you define ws properly
  4. Run the macro or assign it to a button for quick execution.
  5. Check cells B1 for the extracted link and C1 for the clickable hyperlink.
Dim wbName As String
Dim cellFormula As Range

Set cellFormula = ws.Range("A1")
fText = cellFormula.Formula

startPos = InStr(fText, "[")
endPos = InStr(fText, "]")

If startPos > 1 Then
filePath = Mid(fText, 2, startPos - 2)
filePath = Replace(filePath, "'", "") ' remove single quotes

wbName = Mid(fText, startPos + 1, endPos - startPos - 1)
wbName = Replace(wbName, "[", "")
wbName = Replace(wbName, "]", "")

Debug.Print filePath & wbName
ws.Range("B1").Value = filePath & wbName
ws.Hyperlinks.Add Anchor:=ws.Range("C1"), _
Address:=filePath & wbName, _
TextToDisplay:=wbName
End If

Tailoring This Code for Your Needs

  • Range flexibility: Loop through multiple cells with formulas and automate link extraction and hyperlink creation for all.
  • Error handling: Add more robust checks for broken links or non-standard formula formats.
  • User interface: Create a user form that lets users pick ranges or sheets interactively.
  • Dynamic output: Write results to a dedicated worksheet listing all external links in your workbook.

Conclusion

Automating the process to extract linked workbook information from formulas and creating hyperlinks with VBA can significantly increase your workbook management efficiency. Whether auditing external links or creating easy navigation across related files, this VBA snippet provides a solid foundation.

Try enhancing this script by adapting it to your specific workbook structures and enjoy smoother workflows in Excel.

keywords to help others find this post: extract linked workbook, hyperlinks, getting linked workbook info


Do You Need Personalized Help and Custom Solutions?

I have been called a guru and hero more times than I can count, as I am a great listener and truly have a knack for asking the right questions to understand unique business challenges. I am very passionate about crafting tools and processes that work for users of all levels and experience. 

Reach out today and let’s discuss how I can help you and your business!

I also offer one-on-one tutoring for customized learning and upskilling. Visit my consulting page and send a message if you are interested.

Other Resources

Also, consider checking out some great resources on Amazon Disclosure: this is an affiliate link, so I may earn a small commission if you decide to make a purchase which will help cover the cost of hosting this website. 

Please bookmark and subscribe!  I am actively working on adding new, relevant content to help others out! Thanks so much!

Subscribe via Email and Stay Up to Date!

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

If I helped you, please consider leaving a tip via PayPal to support the blog! Thanks!!

Thanks so much for supporting my blog and for helping others too!

calculate only one workbook; calculate only a specific Excel workbook manually without affecting others

How to Calculate Only One Workbook in Excel

How to Calculate Only One Workbook in Excel (On Demand, Without Affecting Others)

If you work with multiple Excel workbooks open at once, you’ve probably noticed that switching calculation modes or performing recalculations applies globally. This means when you press F9 or set calculation to manual or automatic, all open workbooks recalculate or respond – which can be unwieldy and slow, especially when working with large datasets or workbooks with many complex formulas.

But what if you have a particularly resource heavy workbook and want to calculate only one workbook on demand, leaving other workbooks unaffected? This blog post shows you exactly how to do that with a simple VBA trick that changes calculation mode only when you activate a workbook, then sets it back when you leave. This way, you control when and which workbook recalculates — improving performance and workflow.

Why Calculate Only One Workbook Without Affecting Others?

When working in professional environments or complex Excel models, you may:

  • Have multiple workbooks open with large datasets
  • Want to avoid slowing Excel by recalculating everything globally
  • Need a fast way to control calculation to just your active project
  • Prevent unintended data refreshes in other files

Setting Excel to manual calculation can improve speed, but applying it globally can mean other open workbooks don’t update as expected. Conversely, setting calculation to automatic recalculates everything, wasting time and CPU resources.

The best approach is a per-workbook calculation mode, which Excel doesn’t offer natively — but you can mimic it with a clever VBA trick.

How to Control Calculation Mode for a Specific Workbook Using VBA

You can use the Workbook_Activate and Workbook_Deactivate events in VBA to toggle the calculation mode only when your workbook is active.

The VBA Code Explained

Private Sub Workbook_Activate()
Application.Calculation = xlManual
End Sub

Private Sub Workbook_Deactivate()
Application.Calculation = xlAutomatic
End Sub
  • Workbook_Activate() runs every time you switch to the workbook. It sets Excel’s calculation mode to manual, meaning Excel will not recalculate formulas unless you explicitly command it.
  • Workbook_Deactivate() runs when you leave the workbook, switching calculation mode back to automatic, which makes Excel recalculate formulas as usual in other open workbooks.

Step-by-Step Guide: How to Insert This Code into Your Workbook

  1. Open the specific Excel workbook where you want this behavior.
  2. Press Alt + F11 to open the VBA editor.
  3. In the Project pane, find ThisWorkbook under your workbook’s name.
  4. Double-click ThisWorkbook to open its code window.
  5. Paste the VBA code above into this code window.
  6. Save your workbook as a macro-enabled file (.xlsm) to retain the VBA code.
  7. Close the VBA editor.

How It Works in Practice

  • When you switch to this workbook, Excel switches to manual calculation mode (no automatic recalcs).

Keyboard Shortcuts for Calculations in Excel Manual Mode

calculate only one workbook
  • You control exactly when you want to calculate via keyboard shortcuts as shown above.
  • When you switch away from this workbook, Excel switches back to automatic calculation, meaning other workbooks continue calculating as usual.

When your workbook is set to manual calculation upon activation, these shortcuts give you granular control over what to calculate — you can calculate just the active sheet or force recalculation on demand without affecting other workbooks.

Benefits of This VBA Approach

  • Improved Performance: Avoid slowdowns when working with multiple large workbooks
  • Selective Calculation: Only recalculate what you need, when you need it
  • Automatic Mode Switching: No need to remember to switch modes manually, which is very important if working in multiple workbooks
  • Enhanced Workflow: Your Excel environment adapts smoothly to your focused tasks

Final Thoughts

Controlling Excel’s calculation mode on a per-workbook basis enhances productivity when juggling several files. While Excel doesn’t natively support workbook-specific calculation modes, a simple VBA macro like this is a savvy workaround.

By inserting these event-driven macros into your workbook, you ensure calculations run only when you want — keeping other workbooks unaffected, your system responsive, and your workflow smooth.

Try adding this VBA code to your key workbooks today and take back control over Excel’s recalculation behavior! I hope this helped! Now you can share with others how to calculate only one workbook or worksheet at a time.

If you’re interested in me blogging even more advanced Excel VBA tricks to optimize your workflow or want customized guides on Excel automation, feel free to ask in the comments!


Do You Need Personalized Help and Custom Solutions?

I have been called a guru and hero more times than I can count, as I am a great listener and truly have a knack for asking the right questions to understand unique business challenges. I am very passionate about crafting tools and processes that work for users of all levels and experience. 

Reach out today and let’s discuss how I can help you and your business!

I also offer one-on-one tutoring for customized learning and upskilling. Visit my consulting page and send a message if you are interested.

Other Resources

Also, consider checking out some great resources on Amazon Disclosure: this is an affiliate link, so I may earn a small commission if you decide to make a purchase which will help cover the cost of hosting this website. 

Please bookmark and subscribe!  I am actively working on adding new, relevant content to help others out! Thanks so much!

Subscribe via Email and Stay Up to Date!

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

If I helped you, please consider leaving a tip via PayPal to support the blog! Thanks!!

Thanks so much for supporting my blog and for helping others too!

Excel Copilot Icon; Excel Copilot Floating Icon

How to Remove or Hide the Annoying Excel Copilot Floating Icon Permanently

If you use Excel as part of Microsoft 365, you may have noticed the Copilot floating icon that stubbornly follows your cursor around the worksheet. While Microsoft designed it to offer help and AI-driven assistance, many users find this persistent icon distracting and intrusive — especially when it blocks the view of cells or interferes with workflow.

Unfortunately, Microsoft does not currently provide a global or straightforward setting to turn off or permanently hide this Copilot icon in Excel. But there is good news: with a simple VBA macro added to your Personal Macro Workbook, you can automatically hide this icon each time you start Excel, keeping your workspace clean and distraction-free.

Why the Copilot Icon Can Be Annoying

  • The icon constantly moves alongside your active cell, disrupting visual focus
  • No global toggle to permanently disable it means it reappears every workbook or Excel restart
  • Temporary keyboard shortcuts exist but only hide it until you reopen the workbook
  • This constant presence can break workflow rhythm, especially for power users

The Temporary Keyboard Shortcut (Not Permanent)

One quick manual fix discovered is using the keyboard shortcut:

  • Press Alt + Program key (usually the “Menu” key near right Ctrl) then press H
  • This hides the icon only for the current workbook session
  • Once you close and reopen Excel or a workbook, the icon reappears

While this is helpful, it doesn’t solve the recurring annoyance long-term.

The VBA Permanent Fix to Hide the Copilot Icon on Workbook Open

Thanks to the Excel community, a small but powerful VBA macro can be added to your Personal Macro Workbook (PERSONAL.XLSB). This macro runs automatically whenever Excel starts or a new workbook opens, and it hides the Copilot icon programmatically every time.

Here’s the VBA code you need:

Private WithEvents app As Application

Private Sub Workbook_Open()
Set app = Application
End Sub

Private Sub app_NewWorkbook(ByVal Wb As Workbook)
Application.CommandBars("Copilot Menu").Controls("&Hide until I Reopen this Document").Execute
End Sub

Private Sub app_WorkbookOpen(ByVal Wb As Workbook)
If Not ActiveWindow Is Nothing Then
Application.CommandBars("Copilot Menu").Controls("&Hide until I Reopen this Document").Execute
End If
End Sub

How to Set Up the VBA Macro

  1. Open Excel and press Alt + F11 to open the Visual Basic for Applications (VBA) editor.
  2. In the VBA Project pane, locate or create your Personal Macro Workbook (PERSONAL.XLSB).
    • If you don’t already have one, you can create it by recording any simple macro and choosing to save it to the Personal Macro Workbook.
  3. In the VBA Project for PERSONAL.XLSB, right-click on Microsoft Excel Objects, choose Insert > Class Module, and paste the code above into this new module.
  4. Close the VBA editor and save your Personal Macro Workbook.
  5. Restart Excel to allow the macro to run, and the Copilot icon should be hidden automatically.

Important Notes

  • This macro hides the icon “until you reopen the document,” meaning the effect resets per session but automates hiding it each time Excel opens.
  • You can easily enable or disable this by commenting/uncommenting the VBA code lines.
  • No official Microsoft toggle currently exists, so this VBA approach is the best workaround available.

Why This VBA Solution Works Better Than Manual Hiding

  • Automates the process: No need to manually press keyboard shortcuts every session.
  • Invisible to users: Once set, it just works in the background without interrupting workflow.
  • Customizable: Advanced users can extend or modify the macro according to their needs.

Final Takeaway

The persistent Excel Copilot floating icon can be a significant workflow distraction, but you don’t have to live with it. Using a simple VBA macro in your Personal Macro Workbook ensures the icon disappears automatically every time you start Excel or open a workbook, making your spreadsheet work cleaner and more focused.

Until Microsoft offers an official option to toggle the Copilot icon permanently, this VBA workaround remains the best way to kill the annoying Copilot chicklet for good.

Fix incorrect matrix totals in Power BI

Fix Incorrect Matrix Totals in Power BI: A Practical How To Guide

If you work with Power BI, you’ve likely encountered the frustrating issue of incorrect or broken totals and subtotals in matrix visuals—especially when using custom DAX measures. This is a common challenge for Power BI users and often arises when your calculated measures work correctly for individual data rows but fail at the total or subtotal levels. Let’s explore practical techniques to fix incorrect matrix totals in Power BI using advanced DAX patterns, focusing on context evaluation, virtual tables, and the power of SWITCH(TRUE()) logic.

Fix incorrect matrix totals in Power BI: Mastering DAX for Accurate Totals in Your Reports

Fix incorrect matrix totals in Power BI

Why Do Matrix Totals Break in Power BI?

Matrix and table visuals in Power BI aggregate underlying data for totals and subtotals based on the context visible to DAX at each level. Custom measures that depend on row-level context may deliver accurate results for detail rows, but when Power BI computes grand totals, it often loses necessary filters or context, leading to blanks, incorrect sums, or illogical values.

Key causes for broken matrix totals include:

  • DAX measures relying on filters that aren’t present in the total row context.

  • Calculations designed for granular data that don’t make sense when rolled up.

  • Power BI’s automatic aggregation applying logic that doesn’t match business requirements.

Diagnosing and Understanding Matrix Context

Before constructing a fix, it’s vital to analyze how context changes at each level in a matrix visual:

  • Base rows: Both row and column context are present.

  • Subtotals (row or column): Only one of the two contexts is available.

  • Grand totals: Neither row nor column context exists.

A proven method for determining this context is using DAX’s HASONEVALUE function to check for the presence of filters on each axis.

Using SWITCH(TRUE()) for Totals Logic

The core solution involves writing a DAX measure using the SWITCH(TRUE()) construct. This allows you to specify different calculation paths for each possible context combination:

  1. When both row and column context exist (base rows), return your primary measure.

  2. When only row or only column context exists (subtotals), iterate and sum over the filtered context using SUMX and a virtual table.

  3. When neither context exists (grand totals), sum over all possible combinations.

A typical DAX pattern for this uses variables for selected values and a virtual table constructed with CROSSJOIN and ADDCOLUMNS. Here’s what such an approach usually involves:

  • Detect context using HASONEVALUE for each dimension (e.g., month, period).

  • Use SWITCH(TRUE(), …) to order context conditions from most specific (both present) to most general (neither present).

  • For subtotal and grand total contexts, employ SUMX over a virtual table containing all combinations needing to be aggregated.

Best Practices

  • Always write SWITCH(TRUE()) conditions from the most specific to the most general. If you start with general first, your specific logic will never execute due to early exits in SWITCH evaluation.

  • Clearly carve out logic for each level: detail rows, row subtotal, column subtotal, and grand total.

  • Use Tabular Editor or DAX Studio to debug your logic and preview virtual tables to ensure your calculations are on track.

Practical Example Scenario

Suppose you have a Spread Revenue measure that multiplies a simple revenue total by a scaling factor based on lookups. The detail rows work, but all totals show blanks or incorrect values. Using the steps above, you would:

  • Create variables for the selected period and month.

  • Build a virtual matrix table CROSSJOINing all relevant dimensions.

  • Define the measure using SWITCH(TRUE()) and HASONEVALUE checks, aggregating appropriately at each context level.

Voilà—totals and subtotals will now reflect correct logic, tailored to your business needs.

Takeaways

Fixing Power BI matrix totals is fundamentally about understanding DAX row and filter context. By harnessing SWITCH(TRUE()), HASONEVALUE, and virtual tables with SUMX, you gain precision and control over how your visuals aggregate data at every level. Mastering these advanced DAX patterns will eliminate broken totals and elevate the professionalism of your Power BI reports.

Keywords: Power BI, matrix totals, DAX, fixing totals, SWITCH(TRUE()), HASONEVALUE, virtual tables, SUMX, debugging Power BI, Power BI matrix visual, Power BI subtotals, Power BI grand totals, custom DAX measures, Power BI best practices, Tabular Editor, data modeling.


Do You Need Personalized Help and Custom Solutions?

If you get stuck or you would like to explore solutions and automation possibilities, please can reach out to me for help as I do offer consulting services as time allows.  I have over 20+ years’ of expert level experience delivering excellent, custom, strategic solutions in Excel, BI, Access, SharePoint and more. 

I have been called a guru and hero more times than I can count, as I am a great listener and truly have a knack for asking the right questions to understand unique business challenges. I am very passionate about crafting tools and processes that work for users of all levels and experience. 

Reach out today and let’s discuss how I can help you and your business!

I also offer one-on-one tutoring for customized learning and upskilling. Visit my consulting page and send a message if you are interested.

Other Resources

Also, consider checking out some great resources on Amazon Disclosure: this is an affiliate link, so I may earn a small commission if you decide to make a purchase, which will help cover the cost of hosting this website. 

Please bookmark and subscribe!  I am actively working on adding new, relevant content to help others out! Thanks so much!

Subscribe via Email and Stay Up to Date!

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Buy Me A Coffee/Support the Blog 🙂

If I helped you, please consider leaving a tip via PayPal to support the blog! Thanks!!

Thanks so much for supporting my blog and for helping others too!

Excel Export to PDF with Gridlines

Excel Export to PDF with Gridlines and Row & Column Labels

How to Excel Export to PDF with Gridlines and Labels: A Quick Tutorial

Mastering an Excel export to PDF with gridlines and labels is a useful skill when you want your reports to be clear and easy to read—whether you’re sharing financial tables or audit logs with your team. By default, Excel doesn’t always include gridlines, row numbers, or column letters when exporting to PDF, so here’s how to make sure they’re included in your output.

Why Use Gridlines and Labels in Your PDF Exports?

  • Gridlines help visually separate data, preventing confusion and making numbers easier to follow.

  • Row and column labels (like “A, B, C…” and “1, 2, 3…”) make referencing specific data much easier for you and your colleagues.

Combining these can make your exported PDFs clearer, more professional, and easier to audit or review.

Step-by-Step Guide: Excel Export to PDF with Gridlines and Labels

  1. Open Your Worksheet in Excel

  2. Make sure your data is organized the way you want it to appear in the PDF.

  3. Enable Gridlines for Printing

    • Go to the Page Layout tab.

    • In the Sheet Options group, under Gridlines, check the box labeled Print.

    • This ensures Excel will include gridlines when you export or print.

  4. Enable Row and Column Headers (Labels)

    • Still on the Page Layout tab, find the option labeled Headings right next to Gridlines.

    • Make sure the Print checkbox for Headings is also checked.

    • This tells Excel to include the column letters (A, B, C…) and row numbers (1, 2, 3…) on the output.


  5. Adjust the Print Area If Needed

    • Highlight the section of your worksheet you want exported.

    • Go to Page Layout > Print Area > Set Print Area to limit the export to your chosen data.

  6. Preview Before Exporting

    • Go to File > Print or press Ctrl + P for a preview.

    • Double-check that both gridlines and labels are visible in the preview.

  7. Export to PDF

    • Click File > Export > Create PDF/XPS Document or select File > Save As and choose PDF.

    • Confirm your settings and save your file.

That’s it! Now you’ve created an Excel export to PDF with gridlines and labels, making your output highly readable and reference-friendly.

Tips for a Perfect Excel Export to PDF with Gridlines and Labels

  • If you want only some of the sheet to appear, use the Print Area feature.

  • For large tables, consider using the “Repeat Rows at Top” or “Repeat Columns at Left” options under Page Layout > Print Titles so that headers are included on every page.

  • If gridlines look faint, you can adjust their color for better visibility via File > Options > Advanced > Display options for this worksheet > Gridline color.

  • Always preview before you export to avoid surprises!

Conclusion:
Follow these steps for a professional Excel export to PDF with gridlines and labels every time. This makes your data easier to reference, looks more polished, and helps your audience zero in on the right cells in your reports.

If you have other Excel PDF export challenges or want to learn about advanced print setups, let me know in the comments!


Do You Need Personalized Help and Custom Solutions?

I have been called a guru and hero more times than I can count, as I am a great listener and truly have a knack for asking the right questions to understand unique business challenges. I am very passionate about crafting tools and processes that work for users of all levels and experience. 

Reach out today and let’s discuss how I can help you and your business!

 

I also offer one-on-one tutoring for customized learning and upskilling. Visit my consulting page and send a message if you are interested.

 

Other Resources

Also, consider checking out some great resources on Amazon Disclosure: this is an affiliate link, so I may earn a small commission if you decide to make a purchase which will help cover the cost of hosting this website. 

Please bookmark and subscribe!  I am actively working on adding new, relevant content to help others out! Thanks so much!

Subscribe via Email and Stay Up to Date!

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

If I helped you, please consider leaving a tip via PayPal to support the blog! Thanks!!

Thanks so much for supporting my blog and for helping others too!

keywords to help others find this post:

#ExcelTips #PDFExport #GridLines #ExcelTutorial 
Excel PDF export grid lines missing
Excel Page Layout tab settings for PDF export
Excel Page Setup dialog launcher
How to show grid lines in Excel PDF
Excel Sheet tab settings for PDF export
Export Excel file to PDF with grid lines
Excel PDF export row and column headings
Retain grid lines in Excel PDF export
Excel tutorial for PDF export settings
Excel tips for polished PDF exports

Executing SQL in Excel Tool/Template

Amazing Method for Executing SQL Queries in Excel Using VBA (Import Data) – No Need to Use Multiple Applications!

I have found several use cases for my team and I to save time and utilize Excel alone for pulling data via SQL, as opposed to running queries in Access, SSRS, SSMS or Toad and then exporting that data into Excel for manipulation and analysis. There is not only the benefit of saving time by skipping the export/import process, but also in the ability to build templates/files and save them for quick and easy future SQL pulls. The days of needing multiple applications for your SQL pulls to import into Excel are over!

The best use cases I’ve found that support this method are repeatable processes where the same input variables are required each time, and where the query results will not exceed the row limitations of an Excel sheet (~1M). Even in this case, you may find the first two sections of this post useful for learning about constructing and executing SQL queries for use outside of Excel. This alone will likely save you time if you are in the habit of writing long and involved queries with changing criteria.

If you are exceeding the Excel row limit but still want to work in Excel, using Power Pivot can handle this, so you may wish to utilize Power Query instead. Definitely check out my post on utilizing parameters with Power Query here for more information on how to import the data this way.

I have also found this approach to be useful when pulling data from different sources using the same criteria. It saves me lots of time.

In this example, we will construct and then run a simple SQL query using a few parameters/variables that we enter into the spreadsheet.

Follow along so you can see how it works in practice, and then I encourage you to try it out with your own data. Once you master this method, hopefully you will find amazing ways to apply it to your own work!

A copy of the file described in this post is available for purchase – just reach out to me for information. A more complex version that handles wildcards is also for sale.


Setting Up the Variables/Criteria/Parameters for Executing SQL Queries in Excel

My goal will be to run this query: Select * from Store where CreatedDate > #3/1/2022# and State = ‘GA’

  • The two variables in this example will be the created date (3/1/2022) and the State (GA).
  • At the top of my first sheet, we will designate named ranges for the two inputs.
  • Simply type in Created Date in cell A1 to identify the input, then in cell B1, type in 3/1/22.
  • Make B1 a named range – we will call this CreatedDate.
  • Similarly, in A2, type in State, and then in B2, type in GA. Ultimately, you can add in data validation and use lists, but let’s keep it very simple for now.
  • Make cell B2 a named range called State.
    • If you are not familiar with named ranges, the easiest way to make one is to select the cell or cells and then type the name into the dropdown box at the top left next to the formula bar, where the cell address is displayed. Alternately, you can press CTRL+F3 to bring up the Named Ranges dialog box.
SQL Execution in Excel VBA - setting up the inputs for the variables using Named Ranges
Executing SQL Queries in Excel – Setting up Inputs for Variables Using Named Ranges

Constructing the SQL Statement

From here, we can either construct the SQL statement in an Excel sheet or in VBA. I have found that it is far easier to construct in an Excel sheet, especially for complex statements with many criteria. This way certainly allows for more flexibility and better troubleshooting in my opinion. Also, it’s easier to manage from a support standpoint.

  • I will add a new sheet/tab to house the SQL Statement. I will start by typing in the full statement I expect in to A1, just to use as a reference as I build out the statement in the cells below.
  • I then break the statement out line by line, using column A for the variables, and column B for the statements and column C for the joining of statements with variables.
  • Finally, I use the TEXTJOIN function in cell A4 to join together all of the rows in the combined section. I used a space as the delimiter (” “). This ensures proper spacing throughout the resulting SQL statement.
  • I then make cell A4 a named range called SQLStatement.
  • See image below to see how I have achieved all of this.
    • I have included some helper/formula notes on how to format the variables, since the SQL statement has to be properly formatted in order to work.
Executing SQL Queries in Excel variable setup
Construction of SQL Queries in Excel

VBA Code for Executing SQL Statement and Importing the Data

  • Open the VBA editor (Alt + F11).
  • Add a new module.
  • Add a new subroutine. I’ve called mine SQLPull.
  • Very important step – enable the required references. Go to the Tools menu and select References. Select the ActiveX Data Objects 2.8 Library and Recordset 6.0 Library – see the last two checked in the image below (yours may be different versions). Click OK to save.
VBA Project References – ActiveX Data Objects/Recordset

Here is an overview the VBA code I wrote, that is pasted below.

  • Note that it will connect to the database you identify after you update the connection string if needed.
  • It will then execute the SQL select statement and grab the recordset.
  • The code will then write the headers from the query into the cells identified.
  • Next, it will paste the rows that are returned by the SQL query, starting in the specified cell.
  • Finally it will close the connection and end the subroutine.
  • For my applications of this, I like to switch to manual calculation and turn off screen updating because I have found it improves the speed of loading the data. You may choose to leave these alone if working with less data.

I have added commentary and explanations throughout to hopefully help you to modify as needed to support your own needs.

Sub SQLPull()

‘* www.bonbonsguide.com *
‘Importing Data into Excel using a SQL select statement in a cell

Dim Conn As New ADODB.Connection
Dim mrs As New ADODB.Recordset
Dim DBPath, sconnect, sqlstring As String
Dim icols As Long

””””””””””””””””””””””””’
‘Database Name/Path
””””””””””””””””””””””””’
DBPath = STOREDB

‘NOTE:
‘If you are querying a SQL Server or Oracle DB, use the name of the database:
‘DBPath = YourDatabaseName

‘If you are querying an Access Database, use the path to the file in quotes:
‘DBPath = “\myfileserver\Bonbon\MyAccessDB.accdb” OR “F:\Bonbon\MyAccessDB.accdb”

””””””””””””””””””””””””’
‘Connection String
””””””””””””””””””””””””’
‘The DSN is the existing ODBC connection on your PC – this must be set up first!

‘Uncomment the applicable sconnect string for your database and modify as needed. For MS Access, no modifications should be needed.

‘SQL Server using Windows Authentication:
sconnect = “Provider=MSDASQL.1;DSN=STOREDB;DBQ=” & DBPath & “;HDR=Yes’;”

‘ORACLE Connection using an UID/PWD:
‘sconnect = “Provider=MSDASQL.1;DSN=WAREHOUSE;uid=bonbonsguide;pwd=helpsus;DBQ=” & DBPath & “;HDR=Yes’;”

‘MS Access:
‘sconnect = “Provider = Microsoft.ACE.OLEDB.12.0; data source=” & DBPath & “;”

””””””””””””””””””””””””””””””””””””””””””””””””””””’
‘Set Timeouts (These may not be required in your environment)
””””””””””””””””””””””””””””””””””””””””””””””””””””’
Conn.ConnectionTimeout = 200
Conn.CommandTimeout = 200

””””””””””””””””””””””””’
‘Connect to datasource
””””””””””””””””””””””””’
Conn.Open sconnect

””””””””””””””””””””””””’””””””””””””””””””””””””’
‘VBA get SQL Statement from Sheet/Named Range
””””””””””””””””””””””””’””””””””””””””””””””””””’
sqlstring = Range(“SQLstatement”)

””””””””””””””””””””””””””””””””””
‘Get the recordset – this command will execute the SQL Statement’
””””””””””””””””””””””””””””””””””
mrs.Open sqlstring, Conn

””””””””””””””””””””””””””””””””””
‘Return the Header Names
‘”””””””””””””””””””””””””””””””””’
‘If you don’t need the headers or are using your own, comment the block out

‘Where Headers will be pasted:
‘Sheet1 = Sheet identifier – use Sheets(“name of sheet”) to use sheet name instead
‘Cells (4 – indicates row 4, + 3 indicates to start in column C) … Edit this as needed

For icols = 0 To mrs.Fields.Count – 1
Sheet1.Cells(4, icols + 3).Value = mrs.Fields(icols).Name
Next

””””””””””””””””””””””””””””””””””
‘OPTIONAL – SPEED UP IMPORT
””””””””””””””””””””””””””””””””””
‘If retrieving lots of records, it may speed it up if you set calculation to manual during the import process.
‘Setting the screen updating to false may also speed up the import. Comment these out if preferred.
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False

””””””””””””””””””””””””’””””””””””””””””””””””””’””””””””””””””””””””””””’
‘OPTIONAL – CLEAR DATA IN ROWS BEFORE PASTING RECORDSET OR DO OTHER PREP
””””””””””””””””””””””””’””””””””””””””””””””””””’””””””””””””””””””””””””’
‘Add your code here.

””””””””””””””””””””””””””””””””””
‘Paste the Rows/Records
‘”””””””””””””””””””””””””””””””””’

‘Importing rows returned – the range below will be where the data starts – line this up with the headers, one row below.
Sheet1.Range(“C5”).CopyFromRecordset mrs

””””””””””””””””””””””””””””””””””
‘Close the Recordset
””””””””””””””””””””””””””””””””””
mrs.Close

””””””””””””””””””””””””””””””””””
‘Close Connection
””””””””””””””””””””””””””””””””””
Conn.Close

”””””””””””””””””””””””””””””””””””””””””””’
‘Turn automatic calculation and screen updating back on.
”””””””””””””””””””””””””””””””””””””””””””’
Application.Calculation = xlCalculationAutomatic
Application.Calculate
Application.ScreenUpdating = True

End Sub

Wrapping Up

I hope this post about executing SQL queries in Excel helped you out. Below is the final look of my file for this example. I have added a button for the users to click in order to run the VBA code and execute the SQL by assigning the macro. I have formatted so the data returns in a table for easy manipulation and analysis. I have also updated the general formatting and named the sheets.

To save you time, a copy of the file is available for purchase – just reach out to me for information.

I also have another sample template file available that allows you to put multiple criteria in a list and constructs the query accordingly, searching all items. It even allows for the use of wildcards by automatically formulating LIKE statements! Exciting stuff! Contact me if interested in purchasing.

Tool for Execution of SQL Queries in Excel (For Sale)
Tool for Execution of SQL Queries in Excel (For Sale)

tags: executing SQL queries in Excel, SQL in Excel

Do You Need Personalized Help and Custom Solutions?

If you get stuck or you would like to explore solutions and automation possibilities, please can reach out to me for help as I do offer consulting services as time allows.  I have over 20+ years’ of expert level experience delivering excellent, custom, strategic solutions in Excel, BI, Access, SharePoint and more. 

I have been called a guru and hero more times than I can count, as I am a great listener and truly have a knack for asking the right questions to understand unique business challenges. I am very passionate about crafting tools and processes that work for users of all levels and experience. 

Reach out today and let’s discuss how I can help you and your business!

I also offer one-on-one tutoring for customized learning and upskilling. Visit my consulting page and send a message if you are interested.

Other Resources

Also, consider checking out some great resources on Amazon Disclosure: this is an affiliate link, so I may earn a small commission if you decide to make a purchase which will help cover the cost of hosting this website. 

Please bookmark and subscribe!  I am actively working on adding new, relevant content to help others out! Thanks so much!

Subscribe via Email and Stay Up to Date!

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

If I helped you, please consider leaving a tip via PayPal to support the blog! Thanks!!

Thanks so much for supporting my blog and for helping others too!

Excel focus

Excel How to Highlight the Active Cell in Excel with the Focus Cell Feature

Microsoft Excel Tutorial: Easily locate the active cell using shaded crosshairs in the grid – introducing the Focus Cell feature.

How to Highlight the Active Cell in Excel with the New Focus Cell Feature

Working with large Excel spreadsheets can be challenging, especially when you’re trying to keep track of which cell you’re currently editing. If you’ve ever found yourself squinting at your screen, trying to locate the active cell among hundreds of rows and columns, you’re not alone. Fortunately, Microsoft has introduced a game-changing feature called “Focus Cell” that makes navigating Excel spreadsheets significantly easier.

What is the Focus Cell Feature?

The Focus Cell feature is a visual enhancement tool in Excel that provides a prominent highlight around the currently selected cell. Unlike the traditional thin border that surrounds the active cell, Focus Cell creates a much more visible indicator that makes it impossible to lose track of your current position in the spreadsheet.

This feature is particularly valuable for users who work with large datasets, complex financial models, or any spreadsheet where precision and accuracy are critical.

Why You Need Focus Cell

Enhanced Visibility

The most obvious benefit is improved visibility. The Focus Cell feature uses a bold, colored outline that stands out dramatically from the standard cell selection border. This makes it much easier to spot your active cell at a glance, reducing eye strain and improving overall productivity.

Reduced Errors

When you can clearly see which cell you’re working with, you’re less likely to make data entry errors. This is especially important when working with financial data, formulas, or any situation where accuracy is paramount.

Better Navigation Experience

For users who frequently navigate large spreadsheets using keyboard shortcuts, Focus Cell provides instant visual feedback about your current location, making it easier to move around efficiently.

How to Enable Focus Cell in Excel

Enabling the Focus Cell feature is straightforward:

  1. Open Excel and navigate to any spreadsheet
  2. Go to the View tab in the Excel ribbon
  3. Look for the “Focus Cell” option in the Show group
  4. Click the Focus Cell option to enable the feature

Once enabled, you’ll immediately notice the enhanced highlighting around your active cell.

  • Ensure your Excel version supports the feature
  • Verify that the feature hasn’t been disabled by your organization’s IT policies
Excel Focus Cell Settings

Customizing Your Focus Cell Experience

Excel allows you to customize the Focus Cell appearance to match your preferences:

Color Options

You can choose from several color schemes for your Focus Cell highlight. The default is typically a yellow accent, but you can select from any color such as:

  • Blue
  • Green
  • Red
  • Orange

Auto-Highlight

Leave this checked to automatically activate focus cell whenever you search for anything in your workbook, and it is located.

Best Practices for Using Focus Cell

When to Use It

Focus Cell is most beneficial when:

  • Searching for information
  • Working with spreadsheets containing several rows or columns
  • Performing data entry tasks that require precision
  • Collaborating with others who need to follow your navigation
  • Using Excel on smaller screens where standard cell borders are harder to see

Performance Considerations

While Focus Cell is generally lightweight, users working with large spreadsheets (hundreds or thousands of rows) might want to toggle it off during intensive calculations to maintain optimal performance.

Compatibility and Availability

The Focus Cell feature is currently available in:

  • Excel for Microsoft 365
  • Excel 2021
  • Excel for the web (with some limitations)

Note that this feature may not be available in older versions of Excel or certain subscription tiers.

Troubleshooting Common Issues

Focus Cell Not Appearing

If you’ve enabled Focus Cell but don’t see the enhanced highlighting:

Performance Issues

If you notice Excel running slower with Focus Cell enabled:

  • Consider disabling the feature temporarily for large calculations
  • Ensure your system meets Excel’s recommended specifications

The Impact on Productivity

Users who adopt the Focus Cell feature often report:

  • 25% reduction in navigation-related errors
  • Improved comfort during extended Excel sessions
  • Better presentation flow when sharing screens during meetings
  • Increased confidence when working with complex formulas

Conclusion

The Focus Cell feature represents Microsoft’s continued commitment to improving user experience in Excel. By providing a simple yet effective way to highlight the active cell, this feature addresses a common pain point that has frustrated Excel users for years.

Whether you’re a financial analyst working with complex models, a data entry specialist processing large datasets, or a casual Excel user trying to keep track of your household budget, Focus Cell can make your spreadsheet experience more efficient and less error-prone.

Take a few minutes to enable and customize Focus Cell in your Excel installation. Your eyes—and your productivity—will thank you for it.


Have you tried Excel’s Focus Cell feature? Share your experience and tips in the comments below. For more Excel productivity tips and tricks, subscribe to our newsletter and never miss an update.

 

If I helped you, please consider buying me a coffee via PayPal! Thanks!!

bookkeeping template image

Small Business Bookkeeping Template | Excel Spreadsheet | Financial Tracker | Profit & Loss | Income Expense Tracker | Digital Download | TWO FREE BONUSES

bookkeeping template image
bookkeeping template preview

ON SALE! Purchase at a discounted price right via Paypal here on bonbonsguide.com or visit my Etsy Shop!!
https://artofbonbon.etsy.com/listing/4316988571

Transform Your Business Finances in Minutes – Not Hours!
Stop losing sleep over messy finances! This comprehensive bookkeeping template is designed specifically for small business owners, entrepreneurs, and freelancers who want to take control of their money without the headache.

✨ What You Get:
Complete Excel Bookkeeping Template Spreadsheet with 9 pre-built worksheets
Easy Setup Guide – just fill in your business details and go!
Income Tracking for multiple revenue streams (Shopify, Amazon, Etsy, consulting, etc.)
Expense Categories covering all business costs
Monthly Profit Goals with automatic calculations
Annual Overview for tax preparation
Inventory Management system
Materials & Products tracking
Sales Tax calculations

🎯 Perfect For:
Etsy sellers & online shop owners
Amazon FBA sellers
Freelancers & consultants
Service-based businesses
E-commerce entrepreneurs
Anyone tired of shoebox accounting!

💪 Why This Template Works:
✅ Plug & Play Ready – No complex formulas to figure out
✅ Comprehensive Coverage – Income, expenses, profit goals all in one place
✅ Tax-Time Friendly – Organized for easy tax preparation
✅ Scalable – Grows with your business
✅ Time-Saving – Set up once, use all year
✅ Professional – Clean, organized layout

🚀 Benefits You’ll Love:
Save 10+ hours every month on bookkeeping
Never miss a deduction with organized expense tracking
Set and track profit goals monthly
Low stress tax season with organized records
Make better business decisions with clear financial data
Professional presentation for investors or loans

📋 What’s Included:
Setup Sheet – Quick entry of accounts and goals
Income Tracker – Multiple revenue streams
Expense Manager – Add as many categories as you need
Monthly Overview – Profit/loss at a glance
Annual Summary – Year-end totals
Sales Tax Tracking – Breakdown by month
Inventory Tracker – Stock management
Materials Cost – Inventory and cost tracking
Products – Item inventory management

💻 Technical Details:
File Format: Excel (.xlsx) – works with Excel
Instant Download – No waiting!
Lifetime Access – Download anytime
Commercial Use – Use for your business
No Macros – Compatible with all versions of Excel
Compatible with Google Sheets & Numbers, but works best in Excel 🙂

🎁 BONUS #1: Small Business Expense Checklist ($29 Value!)
Don’t leave money on the table! This comprehensive checklist covers 80+ often-missed business deductions that could save you hundreds or even thousands on your taxes.

🎁 BONUS #2: Monthly Financial Review Template ($39 Value!)
Don’t just track your numbers – understand them! This professional template helps you analyze your financial data and create action plans for growth. Turn your bookkeeping into business intelligence!

🔥 LIMITED TIME: Get Organized Today!
Stop procrastinating on your accounting! This bookkeeping template helps many small business owners get their finances organized and profitable.

💬 What Customers Say:
“Finally, a bookkeeping system that actually makes sense! Set up in 15 minutes and saves me hours every month.” – Sarah K.
“Perfect for my Etsy shop. Love how it tracks everything I need for taxes.” – Micah D.
“I wish I had this template when I started my business. Would have saved me so much stress!” – Keiko L.

📞 Questions?
Send a message here on bonbonsguide.com or Etsy if you have any questions about the template!
⚡ Instant Download – Start Organizing Today!

💲 LIMITED TIME OFFER – HUGE SAVINGS WHEN PURCHASING HERE VIA PAYPAL 💲

OR Shop on Etsy: https://artofbonbon.etsy.com/listing/4316988571

free bonuses

🏷️ Tags: bookkeeping template, excel, financial planner, profit loss tracker, income expense sheet, business accounting, etsy seller tools, tax preparation, budget tracker, small business, bookkeeping tool, simple bookkeeping, easy bookkeeping, amazon fba tracker, freelancer finances, entrepreneur tools, business spreadsheet, accounting template, financial organizer, expense tracker, revenue tracker, business planner, digital download

Contact us below with any questions.

← Back

Thank you! Your Message Has Been Sent

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.


Sub ImportCSVWithPowerQuery()
Dim filePath As String
Dim connName As String

filePath = "C:\Data\sales_data.csv"
connName = "SalesDataConnection"

' Check if the connection already exists and delete it
On Error Resume Next
ThisWorkbook.Queries.Delete connName
On Error GoTo 0

' Create a new Power Query connection
With ThisWorkbook.Queries.Add(Name:=connName, Formula:= _
    "let" & vbCrLf & _
    "    Source = Csv.Document(File.Contents(""" & filePath & """),[Delimiter="","", Columns=11, Encoding=65001, QuoteStyle=QuoteStyle.Csv])," & vbCrLf & _
    "    PromotedHeaders = Table.PromoteHeaders(Source, [PromoteAllScalars=true])" & vbCrLf & _
    "in" & vbCrLf & _
    "    PromotedHeaders")

    ' Load the query into a new worksheet
    With ThisWorkbook.Worksheets.Add
        .Name = "Data"
        .Cells(1, 1).LoadFromText Connection:=connName, Destination:=.Cells(1, 1)
    End With
End With

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:
Sub ImportAndTransformExcelDataWithPowerQuery()
    Dim sourceFilePath As String
    Dim sourceWorkbookName As String
    Dim sourceSheetName As String
    Dim connName As String
    Dim queryName As String
    Dim ws As Worksheet
    
    ' Set file path, workbook name, sheet name, and connection/query names
    sourceFilePath = "C:\Data\source_data.xlsx"
    sourceWorkbookName = "source_data.xlsx"
    sourceSheetName = "SalesData"
    connName = "SourceDataConnection"
    queryName = "TransformedSalesData"
    
    ' Delete existing connection and query if they exist
    On Error Resume Next
    ThisWorkbook.Queries.Delete connName
    ThisWorkbook.Queries.Delete queryName
    On Error GoTo 0
    
    ' Create a new Power Query connection
    ThisWorkbook.Queries.Add Name:=connName, Formula:= _
        "let" & vbCrLf & _
        "    Source = Excel.Workbook(File.Contents(""" & sourceFilePath & """), null, true)," & vbCrLf & _
        "    SalesData_Sheet = Source{[Item=""" & sourceSheetName & """,Kind=""Sheet""]}[Data]" & vbCrLf & _
        "in" & vbCrLf & _
        "    SalesData_Sheet"
    
    ' Create a new Power Query query for transformation
    ThisWorkbook.Queries.Add Name:=queryName, Formula:= _
        "let" & vbCrLf & _
        "    Source = #" & connName & "," & vbCrLf & _
        "    RemovedTopRows = Table.Skip(Source, 1)," & vbCrLf & _
        "    RemovedDuplicates = Table.Distinct(RemovedTopRows, {" & _
        "        ""Product"", ""Region"", ""Sales"", ""Date"", ""Quantity"", ""Category""})," & vbCrLf & _
        "    FilteredRows = Table.SelectRows(RemovedDuplicates, each [Sales] > 100)," & vbCrLf & _
        "    SortedRows = Table.Sort(FilteredRows,{{""Date"", Order.Ascending}})," & vbCrLf & _
        "    AddedTotalSales = Table.AddColumn(SortedRows, ""TotalSales"", each [Sales] * [Quantity], Int64.Type)" & vbCrLf & _
        "in" & vbCrLf & _
        "    AddedTotalSales"
    
    ' Load the transformed query into a new worksheet
    Set ws = ThisWorkbook.Worksheets.Add
    ws.Name = "TransformedData"
    ws.Cells(1, 1).LoadFromText Connection:=queryName, Destination:=ws.Cells(1, 1)
    
    ' Format the worksheet
    With ws
        .Range("A1").CurrentRegion.AutoFit
        .Range("A1").CurrentRegion.Style = "TableStyleMedium9"
    End With
    
    MsgBox "Data imported and transformed successfully!"
End Sub

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:

Sub AutomateDataProcessing()
    Dim folderPath As String
    Dim fileName As String
    Dim connName As String
    Dim queryName As String
    Dim ws As Worksheet
    Dim lastRow As Long
    
    ' Set folder path and connection/query names
    folderPath = "C:\Data\"
    connName = "SourceDataConnection"
    queryName = "TransformedSalesData"
    
    ' Delete existing connection and query if they exist
    On Error Resume Next
    ThisWorkbook.Queries.Delete connName
    ThisWorkbook.Queries.Delete queryName
    On Error GoTo 0
    
    ' Initialize a new worksheet for consolidated data
    Set ws = ThisWorkbook.Worksheets.Add
    ws.Name = "ConsolidatedData"
    ws.Range("A1").Value = "Product"
    ws.Range("B1").Value = "Region"
    ws.Range("C1").Value = "Sales"
    ws.Range("D1").Value = "Date"
    ws.Range("E1").Value = "Quantity"
    ws.Range("F1").Value = "Category"
    ws.Range("G1").Value = "TotalSales"
    
    ' Loop through all Excel files in the folder
    fileName = Dir(folderPath & "*.xlsx")
    Do While fileName <> ""
        ' Create a new Power Query connection for each file
        ThisWorkbook.Queries.Add Name:=connName, Formula:= _
            "let" & vbCrLf & _
            "    Source = Excel.Workbook(File.Contents(""" & folderPath & fileName & """), null, true)," & vbCrLf & _
            "    SalesData_Sheet = Source{[Item=""SalesData"",Kind=""Sheet""]}[Data]" & vbCrLf & _
            "in" & vbCrLf & _
            "    SalesData_Sheet"
        
        ' Create a new Power Query query for transformation
        ThisWorkbook.Queries.Add Name:=queryName, Formula:= _
            "let" & vbCrLf & _
            "    Source = #" & connName & "," & vbCrLf & _
            "    RemovedTopRows = Table.Skip(Source, 1)," & vbCrLf & _
            "    RemovedDuplicates = Table.Distinct(RemovedTopRows, {" & _
            "        ""Product"", ""Region"", ""Sales"", ""Date"", ""Quantity"", ""Category""})," & vbCrLf & _
            "    FilteredRows = Table.SelectRows(RemovedDuplicates, each [Sales] > 100)," & vbCrLf & _
            "    SortedRows = Table.Sort(FilteredRows,{{""Date"", Order.Ascending}})," & vbCrLf & _
            "    AddedTotalSales = Table.AddColumn(SortedRows, ""TotalSales"", each [Sales] * [Quantity], Int64.Type)" & vbCrLf & _
            "in" & vbCrLf & _
            "    AddedTotalSales"
        
        ' Load the transformed query into the consolidated worksheet
        lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
        ws.Cells(lastRow + 1, 1).LoadFromText Connection:=queryName, Destination:=ws.Cells(lastRow + 1, 1)
        
        ' Delete the Power Query connection and query after processing
        ThisWorkbook.Queries.Delete connName
        ThisWorkbook.Queries.Delete queryName
        
        ' Move to the next file
        fileName = Dir
    Loop
    
    ' Format the worksheet
    With ws
        .Range("A1").CurrentRegion.AutoFit
        .Range("A1").CurrentRegion.Style = "TableStyleMedium9"
    End With
    
    MsgBox "Data imported, transformed, and consolidated successfully!"
End Sub

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!