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

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.

Microsoft fabric free; Fabric free trial

Should I Upgrade to a free Microsoft Fabric Trial?

If you are exploring Microsoft Fabric and encounter the message “Upgrade to a free Microsoft Fabric Trial” despite already having workspace capacity, here’s what you need to know. This common confusion happens because certain Microsoft Fabric features, especially preview ones like SQL databases and AI Skills, require tenant-level preview feature enablement—even if your workspace is already on a Premium or Fabric capacity.

Why Does Microsoft Fabric Ask for a Free Trial?

When trying to create a SQL database or an AI skill (preview) inside Microsoft Fabric, some users see a prompt requiring them to “Upgrade to a free Microsoft Fabric Trial.” This happens because these preview features are disabled by default at the tenant level for the entire organization. Even if your workspace has an assigned capacity (Premium or Fabric), you need administrator privileges to explicitly enable these preview features.

How to Enable Microsoft Fabric Preview Features

If you are an admin, here’s what to do:

  1. Go to the Microsoft Fabric admin portal.

  2. Look for tenant settings related to preview features.

  3. Enable SQL Database (preview) and AI Skills (preview).

  4. Wait a few minutes (usually between 3 to 15 minutes) for the changes to take effect.

After enabling these settings, you can create a SQL database or AI skill in your workspace without the need to upgrade or start a new trial.

This step is essential because Microsoft Fabric treats these preview features separately from your existing capacity licensing. The message asking to upgrade to a free trial is somewhat misleading—it really means “You need tenant-level preview feature enablement.” This key insight was highlighted by Adam Saxton from Guy in a Cube in his video explanation.

Quick Links to Get Started with Microsoft Fabric Features

Summary and Best Practices

  • Microsoft Fabric preview features like SQL databases and AI Skills require explicit tenant enablement.

  • Even if you have Premium or Fabric capacity, these features are disabled by default for your organization.

  • Admins must enable preview features in the admin portal for users to access them.

  • The free Fabric trial message is a prompt triggered due to disabled preview features, not an actual lack of capacity.

  • After enabling the settings, wait a few minutes before the features become available.


By understanding this distinction, you can avoid confusion and start leveraging Microsoft Fabric’s powerful capabilities without unnecessary trial upgrades. For more tips and updates on Microsoft Fabric and Power BI, follow the community experts and stay tuned for new videos and tutorials.

keywords: Microsoft Fabric freeMicrosoft Fabric trialMicrosoft Fabric preview features, and Microsoft Fabric SQL database.

Feel free to share your questions or experiences with Microsoft Fabric preview features in the comments!

If you’re ready to dive deep into Microsoft Fabric and its rich capabilities, start creating your first SQL database or AI skill today using the official docs linked above. Unlock the full potential of your data analytics journey!

 

 

 

 

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!

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.

How To Calculate Averages Per Day In Power BI

How To Calculate Averages Per Day In Power BI Using DAX: A Practical Guide for 2025

When analyzing sales or any time-sensitive data in Power BI, understanding average performance per day can provide far more actionable insights than just looking at total sales or aggregated sums. Whether you’re measuring sales transactions, website traffic, or social media interactions, calculating the average sales per day in Power BI dynamically fuels smarter business decisions.

In this guide, you will learn a simple but powerful DAX formula technique to calculate averages per day that dynamically adjust across different customers, time periods, or product categories.

How To Calculate Averages Per Day In Power BI

Why Calculate Average Sales Per Day?

Absolute sales totals simply show overall volume but can be misleading if sales happened unevenly across the days. For example, a customer might have a big sale one day and no sales other days, making the average daily sales a better reflection of ongoing engagement or revenue generation.

Calculating the average per day helps to:

  • Track performance trends over time
  • Compare sales consistency across customers or regions
  • Analyze monthly or yearly performance with per-day precision
  • Optimize forecasting and target-setting processes

Understanding the Data Model

Before diving into DAX, you should have a data model in Power BI with tables such as:

  • Sales transactions (with sales amount, date, customer, product, region/area)
  • Date table (a fully connected calendar table for proper time intelligence)

This foundational setup allows you to slice and dice data dynamically by customers, months, years, or any relevant dimension.

The Core DAX Formula Explained

At the heart of this method is the usage of two essential DAX functions:

  • AVERAGEX() — iterates over a table and averages an expression evaluated for each row
  • VALUES() — generates a distinct list of dates within the current filter context

Here’s the conceptual approach:

  1. For each customer (or chosen dimension),
  2. Iterate through every distinct date in the current context,
  3. Calculate total sales for that date,
  4. Average all daily totals to get the average sales per day for that customer.

Sample DAX Formula for Average Sales Per Day

textAverage Sales Per Day = 
AVERAGEX(
    VALUES('Date'[Date]),
    CALCULATE(SUM('Sales'[TotalRevenue]))
)
  • VALUES('Date'[Date]) creates a virtual table of all dates currently in context (say for a filtered month or customer).
  • CALCULATE(SUM('Sales'[TotalRevenue])) calculates total sales for each date during iteration.
  • AVERAGEX averages those daily totals to produce the average sales per day.

How to Use the Formula Dynamically

When you add this measure to a Power BI visual, you can slice it by:

  • Customers to see average daily sales per customer
  • Months or years to analyze trends in different periods
  • Regions or product categories to evaluate average sales patterns across segments

Because the formula responds to your report filters, it automatically adapts to whatever dates or dimensions you select, making it a flexible and powerful metric.

Benefits of This Approach

  • Simplicity: A short, easy-to-understand DAX expression avoids complex calculations.
  • Dynamic Insight: Changes in filters instantly update the average calculations.
  • Versatility: Works across various dimensions without rewriting the formula—just place on different visuals.
  • Accurate Context Handling: Uses the date table effectively to handle partial months or custom time frames without errors.

Final Thoughts

If you want to deliver precise and insightful reports in Power BI, learning how to calculate averages per day with DAX is fundamental. This technique not only sharpens your data storytelling but empowers stakeholders to make data-driven decisions with confidence.

Power BI’s ability to dynamically slice data combined with powerful DAX functions means you can unlock valuable daily average metrics without heavy coding or manual calculation errors.

Try this formula on your own sales data model and watch how it reveals new perspectives on customer behavior and business performance trends over time.

I hope this blog post has truly shown you how to calculate averages per day in Power BI, since calculating averages for time-based data is useful in so many applications!

Keywords to help others find this post:

Power BI average sales per day, Calculate averages per day Power BI, DAX average sales calculation,Power BI time-based average calculations, Average sales per customer Power BI


Do You Need Personalized Help/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!

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

Power BI error bars for uncertainty visualization

How To Utilize Error Bars In Power BI To Visualize Uncertainty In Your Data

How to Use Power BI Error Bars for Uncertainty Visualization: Step-by-Step Guide

Power BI error bars for uncertainty visualization are a game-changing feature, enabling data analysts and business users to represent confidence intervals, forecast uncertainty, and data variability directly on their line charts. In this comprehensive tutorial, we’ll explore everything you need to know: from enabling the feature to advanced interactivity through parameters.

What Are Error Bars and Why Do They Matter in Power BI?

When you’re visualizing forecast data or any measurement with natural variability, showing point estimates alone can be misleading. Power BI error bars for uncertainty visualization allow you to display possible ranges for each data point, communicating confidence and transparency in your data storytelling. This is especially critical for:

  • Sales forecasts with seasonality

  • Scientific measurements with instrument error

  • Survey results or estimates

By making uncertainty explicit, you empower your viewers to interpret results more accurately and make informed decisions.

Enabling Power BI Error Bars for Uncertainty Visualization

Before using error bars, make sure your version of Power BI Desktop supports them (this step is only needed in older versions):

  • Go to File > Options > Preview features.

  • Enable “Error Bars.”

  • Restart Power BI Desktop.

Pro tip: Error bars settings may continue to evolve, so always update Power BI for the latest enhancements.

Building Your First Power BI Error Bars for Uncertainty Visualization

1. Set Up Your Base Visual

Start with a basic line chart displaying your key measurement (e.g., Monthly Sales).

  • Drag your date/time to the X-axis and your main value (e.g., Sales) to the Y-axis.

2. Define Upper and Lower Bound Measures

You need two measures for each point—Upper Bound and Lower Bound—that will define the error bars.

Example DAX for relative error bars:

text
Sales Upper Bound = SUM(Sales[Amount]) + 5000
Sales Lower Bound = SUM(Sales[Amount]) - 5000

Place these measures in the chart’s “Error Bars” section.

You can also use dynamic calculations:

text
Sales Upper Bound = SUM(Sales[Amount]) * (1 + [Uncertainty Parameter])
Sales Lower Bound = SUM(Sales[Amount]) * (1 - [Uncertainty Parameter])

3. Configure the Error Bars Visual

Open the Analyze pane:

  • Under “Error Bars,” toggle On.

  • Choose “Relative” (fixed increase/decrease) or “Absolute” (direct upper/lower value).

  • Customize style: error lines, bars, or shaded areas for visual clarity.

Advanced Technique: Interactive Power BI Error Bars for Uncertainty Visualization with Parameters

Take uncertainty modeling further by letting viewers control the amount of uncertainty shown, using Power BI’s What-If parameters.

Steps:

  1. Create a What-If Parameter:

    • On the Modeling ribbon, select “New Parameter.”

    • Set as decimal, with a reasonable range (e.g., 0.0 to 0.3 for 0–30%).

  2. Reference the Parameter in Your Bounds:
    Update your upper/lower bound measures to multiply the main value by (1±parameter value).

  3. Add Parameter as Slicer:
    Place the parameter on the report canvas. Now, users can adjust a slider and watch the uncertainty range change interactively.


Why is this powerful?
Viewers can explore best-case/worst-case outcomes, stress test forecasts, or tailor visuals to their own risk tolerance—making Power BI error bars for uncertainty visualization remarkably interactive.

Practical Tips and Troubleshooting

  • Relative vs. Absolute: Use relative error bars for a fixed increment (±X), absolute for data-driven bounds (e.g., statistical deviations).

  • Labeling: Consider adding text or tooltip explanations so viewers grasp what the error bars represent.

  • Complex models: For forecast models with statistical confidence intervals, you can calculate upper/lower bounds using DAX or integrate with external R/Python forecasts.

  • Data Model: Store parameter values and error range calculations in your data model for auditability and reusability.

Real-World Scenarios for Power BI Error Bars for Uncertainty Visualization

  • Sales Forecast Dashboards: Show forecast ranges during high volatility periods.

  • Scientific Data: Display measurement error for each point, letting stakeholders see the instrument precision.

  • Customer Surveys: Represent margin of error due to sample size.

Conclusion

Embracing Power BI error bars for uncertainty visualization not only makes your reporting more honest but also improves trust and understanding among your audience. By combining error bars with interactive parameters, you offer viewers a dynamic, transparent, and engaging analytic experience.

With these steps, you’ll unlock the full potential of Power BI error bars for uncertainty visualization, turning simple line charts into robust storytelling tools.

Would you like a downloadable sample file, sample DAX, or even deeper dives into the DAX logic? Let me know in the comments!

Chart Screenshot/Example

Power BI error bars for uncertainty visualization

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!

How To Copy DAX Measures (Multiple) From Different Reports In Power BI

One of the frequent pain points in Power BI development is the lack of a native, built-in method for copying multiple DAX measures between reports. As your analytics practice grows, the need to reuse calculations, KPIs, or business logic across multiple Power BI files becomes both common and essential. Fortunately, there’s an efficient workaround using Tabular Editor— a popular external tool that comes in both free and paid versions —that can dramatically speed up your workflow. This post will show you the step by step method to easily copy DAX measures from one report to another.

The Challenge: No Native Bulk Measure Copy in Power BI

Power BI Desktop does not currently provide a feature for multi-selecting and copying measures from one .pbix report to another. Attempting to manually recreate measures is time-consuming and increases the risk of error, especially in projects with complex calculations.

The Solution: Tabular Editor to Copy DAX Measures

Tabular Editor allows users to access and manipulate the semantic model of a Power BI file directly. Using this tool, you can copy one, several, or even all measures from a source report, then paste them directly into your destination report—saving hours of work and frustration.

Head over to either https://www.sqlbi.com/tools/tabular-editor/ or https://tabulareditor.com/downloads

Download the Tabular Editor program and install the version that best suits your needs.

Once you install the program, when you next open the Power BI app, you should see the External Tools menu available. If it is not visible, try rebooting. If it is still not visible, reach out to your trusted IT support for further assistance if needed.

Step-by-Step Guide to Bulk Copy Measures

1. Open Both Source and Target Reports:
Launch Power BI Desktop and open both your source (.pbix) and destination reports simultaneously.

2. Launch Tabular Editor:
With your source report active, open Tabular Editor from the ‘External Tools’ menu. Do the same for your target report in a separate Tabular Editor window.

3. Prepare a Target Measure Table:
Ensure your target report has a table to receive the imported measures. If it doesn’t, create a blank “measures” table.

4. Select and Copy Measures:
In the source Tabular Editor window, select all the desired measures (use Ctrl+Click or Shift+Click for bulk-selection). Ctrl + C to Copy or select Copy from the Edit menu.

5. Paste into Target Report:
Switch to the destination Tabular Editor window. Right-click the appropriate table and Ctrl+V or select Paste from the Edit menu. All copied measures will appear.

6. Save Changes:
Click “Save” in Tabular Editor, and your new measures will become available in the target Power BI report.

6. Ensure Fields/Tables Match:
Return to Power BI and review the measures. Ensure that all tables and fields exist, or modify the measures as needed if there are any differences.

Why This Method Works

Tabular Editor interacts directly with the tabular data model behind your .pbix file, unlike Power BI’s own interface, which restricts mass management of measures. This approach is not officially supported by Microsoft, but it is widely used and greatly increases productivity within the Power BI community.

Tips and Caveats

  • Quick Measures: Some complex or “Quick Measures” may require additional adjustment after copying, especially if you have differences in your table/column structure.

  • Annotations: For optimal compatibility, remove format annotations via the Advanced Scripting tab in Tabular Editor before copying, especially if you run into errors.

  • Free and Paid Versions: The described process works with both the free and paid versions of Tabular Editor.

Conclusion

Reusing DAX measures across reports no longer needs to be tedious. With Tabular Editor, you can bulk copy and paste measures within a few clicks, supercharging your Power BI workflow. For teams and consultants frequently working with standardized metrics, this is an indispensable part of your Power BI toolkit.

Tabular Editor Screenshot

Copy DAX Measures in Tabular Editor program

If you’d like more advanced automation tips or guides on optimizing your Power BI modeling practices, let us know in the comments!

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!!