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!

Hosting Your Own AI/Local LLM On Your PC (For Free)!

Hosting your own AI local LLM (Large Language Model) can offer several benefits, especially for individuals and organizations looking to leverage advanced AI capabilities while maintaining control and security. Here are some key advantages:

Control and Customization:

  • Tailored Solutions: Customize the model to fit specific business needs, industries, or datasets.
  • Data Privacy: Ensure that sensitive data remains within your control and is not shared with external providers.

Security:

  • Data Security: Protect sensitive information by hosting the model on-premises or in a secure cloud environment under your control.
  • Compliance: Meet regulatory and compliance requirements by having full control over data handling and model deployment.

Latency and Performance:

  • Reduced Latency: Host the model closer to where it is needed, reducing latency and improving response times.
  • Optimized Performance: Fine-tune the model and infrastructure for optimal performance tailored to your specific use case.

Cost Efficiency:

  • Long-term Savings: While initial setup costs can be high, hosting your own model can be more cost-effective in the long run, especially for large-scale deployments.
  • Avoid Vendor Lock-in: Reduce reliance on third-party services and potential vendor lock-in, giving you more flexibility in choosing solutions.

Scalability:

  • Flexible Scaling: Easily scale the model and infrastructure to meet changing demands without relying on third-party providers.
  • Resource Allocation: Allocate resources more efficiently based on your specific needs and budget.

Innovation and Research:

  • Advanced Research: Engage in cutting-edge research and development by leveraging the full capabilities of the model and infrastructure.
  • Experimentation: Conduct experiments and iterate on models without the constraints of third-party services.

Integration:

  • Seamless Integration: Integrate the model with existing systems and workflows more easily, ensuring a cohesive and efficient operation.
  • Custom APIs: Develop custom APIs and interfaces tailored to your specific requirements.

Resilience and Reliability:

  • Uptime: Ensure high availability and uptime by managing the infrastructure directly.
  • Disaster Recovery: Implement robust disaster recovery and backup strategies to protect against data loss and downtime.

By hosting your own LLM, you gain significant control over your AI infrastructure, enabling you to tailor solutions to your specific needs while maintaining security and performance. Read on as we walk through the process together.

Instructions (Windows)

  • Download Ollama. Head on over to ollama.com and download for Windows.
  • Install the application.
host your own local LLM - installation image for Ollama.
  • In the meantime, head over to the models page on the Ollama website and read through them to decide which you would like to install. Each model has a command to install it next to the tags. In the example below, it is ollama run llama3.3; copy this command.
  • Once Ollama is installed, start the application from the Start menu.
  • Open a command prompt (Windows logo key + R, type cmd and hit enter).
  • When the command prompt window opens, paste the command you copied from the model page and hit enter.
  • Close Ollama by typing /bye and hitting enter.
  • Next, download the appropriate version of Docker Desktop for your computer.
  • Go to the Open UI github here and scroll to the installation instructions.
  • Copy the “If Ollama is on your computer” command.
  • Run this command in the command prompt. The package is large and may take several minutes to download and install.
  • After the installation is complete, go to the Docker application and note the open-webui container.
  • In your browser, head to http://localhost:3000/
  • Note: On my machine, I had to stop and restart the Docker container the first time; if you are having an issue, try that first.
  • Select the model at the top.
  • You now have a lovely interface to interact with your model! The possibilities are endless.

Referencing an Excel Sheet With An Apostrophe in its Name – Solved!

The Problem – Apostrophes in Sheet Names

You are trying to use a formula to reference an Excel Sheet with an apostrophe in its name and you keep receiving an error message or a #REF! reference error.

The Solution (Very Easy!)

Great news! Simply replace the apostrophe with two apostrophes in your formula. That’s right, two consecutive apostrophes, not a quote. Very simple solution indeed!

Below I provide two examples. You can manually update the name in your formula (or in the cell you are referencing if using an indirect lookup), or if working with many sheet names, you may opt to use the substitute solution shown below (formula displayed in E5).

=substitute(A4,"'","''")

The substitute can be nested in an indirect formula also.

Excel Sheet with an apostrophe solution
Excel Sheet With An Apostrophe Solution

Please comment below on any other challenges you would like for me to cover. I am contemplating doing a quick solution series in this format!

Also, be sure to check out Dose for Excel (click the image below)! Add over 100 functions to Excel to increase your productivity and more!  Disclosure: this is an affiliate link, so I may earn a small commission if you decide to purchase the add-in. Thanks for supporting my blog!

Dose for Excel - +100 Functions

Some topics addressed in this post:
Ref Error in lookup
#REF! Error in lookup
Ref Error in formula
#REF! Error in formula
How to fix ref error in Excel from apostrophe
Apostrophe in Excel sheet name issue



Organize your DAX measures

How To Organize Your DAX Measures in Power BI Folders and Make Finding Them A Breeze

As you progress in Power BI, you will gradually be working with more DAX measures and calculations. As a result, things can easily get cluttered. Today you will learn a few valuable tips and tricks on how to organize your DAX measures for a more efficient workflow. Hopefully this will help you and become a standard practice!

Watch the video for step by step instructions and a full explanation.

To summarize, Reid shows us how to add a new table and move our measures to it so they are together in one place.

He then shows us how to convert this into a folder, and then subsequently create subfolders to further organize your DAX measures in the model. Reid continues on to show us how we can have a measure in multiple locations if it makes sense.

What a great way to manage the measures as they grow in number!

***** Video Details *****
00:00 Introduction
00:33 Root folders
01:32 Subfolders
03:30 Actual Amount VTB

***** Learning Power BI? *****
FREE COURSE – Ultimate Beginners Guide To Power BI – http://portal.enterprisedna.co/p/ultimate-beginners-guide-to-power-bi
FREE COURSE – Ultimate Beginners Guide To DAX – http://portal.enterprisedna.co/p/ultimate-beginners-guide-to-dax
FREE – Power BI Resources – http://enterprisedna.co/power-bi-resources
FREE – 60 Page DAX Reference Guide Download – https://enterprisedna.co/dax-formula-reference-guide-download/
Enterprise DNA Membership – https://enterprisedna.co/membership
Enterprise DNA Online – http://portal.enterprisedna.co/
Enterprise DNA Events – https://enterprisedna.co/enterprise-dna-events-page/

#EnterpriseDNA #PowerBI #PowerBIDesktop #PowerBITutorial #DAX #DAXTutorial

multiply an entire column

Multiply an Entire Column by a Number in Excel (without using a formula)

Are you looking to multiply an entire column or range by a number? Get ready for a quick and easy tutorial!

You could always use another column and have the formula to do this, but this way is quick and easy if you do not plan on changing the values.

  1. All you need to do is have the number that you want to multiply in a cell (any cell).
  2. Now copy this cell and paste as special in the cells/range/column where you want to multiply it.
  3. In the Paste Special dialog box, choose the multiply option (in the Operation section) and click OK.  Your column/cells/range should be multiplied!
  4. If desired, can delete the cell that has the value which you multiplied by.

The resulting data is static/fixed so there’s no need to change any formula to value after multiplying using the paste special function.

Multiply An Entire Column

As always, I hope this helped you! Simple solutions are the best!


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

Subscribe for more great content!

Delete Every Other Row or Column in Excel (using Formula or VBA)

Today we are going to explore various ways to delete every other row or delete every other column in Excel. VBA macro code is included to help you on your way if that is the path you choose.

Additionally, we will also cover how to delete every third/fourth/fifth row or column in Excel.

To delete alternate rows, you can use a helper column and use a formula that helps you identify alternate rows. This could be done by using the ISEVEN function that checks each row number and returns TRUE if the row is even and false if it isn’t.

Once you have this, you can easily filter the rows with FALSE in the helper columns and delete these.

In case you want to delete every third row, you need to use the MOD function to identify every third row. Once you have it, you can easily filter and delete every third row or every fourth row.

I also cover a method to use a simple VBA code to delete alternate rows in Excel.

Below is that VBA CODE TO DELETE ALTERNATE ROWS:

Sub Delete_Every_Other_Row()
Dim Rng As Range
Set Rng = Application.InputBox("Select the Range (Excluding headers)", "Range Selection", Type:=8)
For i = Rng.Rows.Count To 1 Step -2
If i Mod 2 = 0 Then
Rng.Rows(i).Delete
End If
Next i
End Sub

When it comes to deleting alternate columns, you cannot filter these. You can instead sort and bring all those columns together that you want to delete.

I cover a simple method that uses the MOD function to identify alternate columns and then sort these from left-to-right to bring these together. Once you have these in one place, you can select and delete these.

And there is also a VBA code that you can use to delete alternate columns.

Below is the VBA CODE TO DELETE ALTERNATE COLUMNS

Sub Delete_Every_Other_Column()
Dim Rng As Range
Set Rng = Application.InputBox("Select the Range (Excluding headers)", "Range Selection", Type:=8)
For i = Rng.Columns.Count To 1 Step -2
If i Mod 2 = 0 Then
Rng.Columns(i).Delete
End If
Next i
End Sub

Subscribe to this YouTube channel to get updates on Excel Tips and Excel Tutorials videos – https://www.youtube.com/c/trumpexcel

You can find a lot of useful Excel resources on the following site: https://trumpexcel.com/

#Excel #ExcelTips #ExcelTutorial

View on YouTube

Power Query Filter Rows by NOT Contains Criteria – Single Formula Solution

Learn how to filter a table based on NOT Contains Criteria. Download an example workbook here.

Easy step by step instructions below.  See a single formula solution using the functions Splitter.SplitByAnyDelimiter, List.Count and Table.SelectRows. Amazing formula solution from Power Query Poet, Bill Szysz.

Please watch the video if you’d like for a guided walkthrough and also another method that can be useful for multiple tables.  

Criteria Table

  1. Create a new, separate table with the list of terms you will want to exclude. Name the table “NoCriteria”.
  2. Add the excluded item (NoCriteria) table to Power Query – click within table, under Data menu, choose From Table/Range, which is in the Get and Transform data section.
  3. In the Power Query window, select the Transform menu and click convert to list.
  4. Under the File menu, choose Close and Load To, then choose Connection Only.

Building the Filtering via Power Query

  1. Add or create the list/table that will ultimately be filtered.
  2. Click any cell within the table that will be filtered. Add the excluded item table to Power Query (click within table, under Data menu, choose From Table/Range, which is in the Get and Transform data section).
  3. In the Power Query window, click the Add Column menu, and select Custom Column.
  4. In the window that opens, type this:

    = Table.SelectRows(#”Changed Type”, each List.Count (Splitter.SplitTextByAnyDelimiter(NoCriteria)([PRODUCT_NAME]))=1)

  5. Change [PRODUCT_NAME] in that text to your own column in the table that you will be filtering on if it is different.
  6. Select the statement you have typed in and copy it (you will need to paste this formula in a following step).
  7. Click OK. You will see that the formula you typed was changed by the program and a column was added.
  8. To change the formula back, click the menu bar, highlight the entire text and then replace by pasting in the formula you copied. Hit enter.
  9. The extra column should be removed and the table should be filtered on you criteria from the NoCriteria table.
  10. Click the File menu, choose Close and Load To, then choose where you would like the newly filtered table loaded to.

Any time changes are made to the exclusion list, you will need to refresh the filtered table. Simply right click any cell within the filtered table, and select Refresh.

 

Bonus – Filtered table with the excluded items only (not shown in video)

You can additionally create a filtered table that only includes the terms in your NoCriteria table!  

  1. To do this, go into Power Query.  Right click on your filtered table and click Duplicate.
  2. In that new table, you will very slightly change the existing formula in your Power Query to not equal one (see orange text):

    = Table.SelectRows(#”Changed Type”, each List.Count (Splitter.SplitTextByAnyDelimiter(NoCriteria)([PRODUCT_NAME]))<>1)

  3. Hit enter.  The table should now only filter on the items in your exclusion list, instead of including them.
  4. Click the File menu, choose Close and Load To, then choose where you would like the newly filtered table loaded to.

View on YouTube

Create A Gantt Chart In Power BI With A Matrix Visual

Managing projects effectively requires clear visuals that communicate timelines and task progress at a glance. While Power BI offers many visuals, building a Gantt chart using the built-in Matrix visual is a powerful technique for showing detailed project timelines without needing custom visuals. This blog post walks through the key concepts and steps for creating a Power BI matrix Gantt chart, perfect for project managers and data analysts alike.

What is a Matrix Gantt Chart in Power BI?

A Gantt chart visually represents project schedules by showing tasks as bars mapped over calendar dates. Unlike using custom Gantt chart visuals, you can cleverly use Power BI’s matrix visual combined with DAX formulas and conditional formatting to mimic a Gantt chart. This approach is advantageous because it leverages native visuals without extra installation, is highly customizable, and integrates seamlessly with your existing data models and filters.

Why Use a Matrix Gantt Chart?

  • Native Power BI Visual: No need for third-party downloads or licensing.
  • Dynamic and Interactive: Integrates with slicers and filters for dynamic timeline updates.
  • Detailed Task View: Offers drill-down capabilities across project hierarchies.
  • Full Control Over Design: Customize colors and styles through conditional formatting rules.

Step-by-Step Guide to Creating a Power BI Matrix Gantt Chart

  1. Prepare Your Data Model
  2. Your dataset should include at least these columns:
    • Project or Task Name
    • Start Date
    • End Date or Duration(Optional)
    • Task Status or Category
    • You also need a Date table in your data model to serve as a timeline backbone.
  3. Establish Relationship sConnect your Date table to your Project table using the Start Date (and possibly End Date) fields to enable time intelligence across visuals.
  4. Create a Matrix Visual
    • Place Project Name (and subcategories if needed) in the Rows.
    • Place Date from the Date table in the Columns.
  5. Create a DAX Measure to Highlight Task DurationWrite a measure that returns 1 if a given date falls within the task start and end dates and 0 otherwise. This will be the basis for your Gantt bars.Example simplified logic: TaskActive = IF( SELECTEDVALUE('Date'[Date]) >= MIN('Projects'[StartDate]) && SELECTEDVALUE('Date'[Date]) <= MAX('Projects'[EndDate]), 1, 0 )
  6. Apply Conditional Formatting Use conditional formatting on the Matrix’s Values field. Format the background color to:
    • Show a distinct color (e.g., gold or blue) when the TaskActive measure equals 1. Show a lighter or neutral color when 0.
    This creates the visual bars of the Gantt chart within the matrix cells.
  7. Enhance Your Visual
    • Turn off subtotals for clarity.
    • Use slicers to filter projects or timelines dynamically.
    • Add tooltips with task details.
    • Customize colors by task status or category using additional measures and formatting rules.

Benefits of Using a Matrix Gantt Chart in Power BI

  • Cost-effective: No licensing or external visuals needed.
  • Integrated experience: Aligns with your Power BI reports and dashboards perfectly.
  • Scalable: Works well from small projects to complex multi-phase portfolios.
  • Customizable: You control colors, interactivity, and granularity.

By leveraging Power BI’s matrix visual combined with smart DAX measures and conditional formatting, you can build a robust, customizable Gantt chart tailored to your project management reporting needs. Start experimenting with your project data today and unlock richer timeline insights right inside Power BI!

Other Options/Resources

For those interested in alternative approaches, there are also custom Gantt chart visuals available in Power BI Marketplace, but the matrix method provides unmatched flexibility and control for many project reporting scenarios.

Delete Rows Based on a Cell Value (or Condition) in Excel [With and Without VBA]

Managing data efficiently in Excel often means removing unwanted rows that meet certain criteria—such as rows with specific text, dates, numbers, or even partial matches. Whether you’re cleaning up a small spreadsheet or preparing a large dataset for analysis, understanding how to delete rows based on cell values will help you keep your data tidy and relevant. This guide explores multiple techniques to remove rows in Excel according to specific cell values, making your data management tasks faster and more accurate regardless of your proficiency with Excel features or VBA automation.

This tutorial explains several methods to remove rows from an Excel worksheet based on the value in a specific cell or according to set conditions.

Here are four different approaches you can use to delete rows depending on their cell values:

  1. Using Filters:
    Apply a filter to your data, select the criteria you want to remove (for example, rows where “Status” is “Inactive”), and delete all the filtered rows at once.
  2. Sorting Data:
    Sort your data by the column you want to filter (e.g., sort by “Department” so all “Sales” records are grouped together) and then delete all the matching rows in one go.
  3. Finding Cells with Specific Values:
    Use Excel’s “Find” feature to locate cells with a value like “Expired”, select those rows, and delete them all together.
  4. VBA Automation:
    Automate row deletion by using a VBA macro that filters and deletes based on your criteria (e.g., remove all rows where “Order Status” is “Cancelled”).

Tip:
Choose the method that best fits your dataset’s structure and your workflow. Remember, deleting a row removes everything in that row—including all data to the left and right. If you only want to clear certain cells but keep the row and other information, consider using the filter and dummy column trick, or manually clearing cell contents instead of deleting the row.

Wildcard Matching Example:
With Find and Replace, you can use wildcards for powerful matching. For instance, to find every region ending with “East” (such as “North-East” or “South-East”), type “*-East” (the asterisk stands for any sequence of characters).

Example VBA Codes

Delete All Rows Where “Status” is “Inactive”:

textSub DeleteRowsWhereInactive()
    ActiveCell.AutoFilter Field:=3, Criteria1:="Inactive" 'Assumes the Status column is column 3
    ActiveSheet.AutoFilter.Range.Offset(1, 0).Rows.SpecialCells(xlCellTypeVisible).Delete
End Sub

Prompt User before Deleting Rows Where “Order Status” is “Cancelled” Without Deleting the Entire Row:

textSub DeleteCancelledStatusCells()
    Dim MsgboxAns As Integer
    ActiveCell.AutoFilter Field:=4, Criteria1:="Cancelled" 'Assumes Order Status is column 4
    MsgboxAns = MsgBox("Are you sure you want to delete these cells?", vbYesNo + vbQuestion)
    If MsgboxAns = vbYes Then
        ActiveSheet.AutoFilter.Range.Offset(1, 0).Rows.SpecialCells(xlCellTypeVisible).Delete (xlShiftUp)
    End If
End Sub

Delete Rows in an Excel Table Where “Department” is “Support”:

textSub DeleteRowsinTableForDepartment()
    Dim Tbl As ListObject
    Set Tbl = ActiveSheet.ListObjects(1)
    ActiveCell.AutoFilter Field:=2, Criteria1:="Support" 'Assumes Department is column 2
    Tbl.DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
End Sub

**#Excel #ExcelTips #A #ExcelTutorial

Let me know if you need more tailored code or examples for your data!

Cross Selling Matrix Deep Dive – Power BI & DAX Tutorial

In this tutorial we cover how to create a cross selling matrix.

This requires a full understanding of the concept of ‘context’ and much more.

Some advanced DAX formulas are covered in detail, especially table functions.

Plenty of great techniques to learn about during this one.

Enjoy!

Sam

***** Learning Power BI? *****

FREE COURSE – Ultimate Beginners Guide To Power BI – http://bit.ly/2SGof6C

FREE COURSE – Ultimate Beginners Guide To DAX – http://bit.ly/2AyEb3P

FREE – Power BI Resources – http://bit.ly/2C2aBn3

FREE – 60 Page DAX Reference Guide Download – http://bit.ly/2AyEc7T

Learn more about Enterprise DNA – http://bit.ly/2RacRD3

Enterprise DNA Membership – http://bit.ly/2AAqa5u

View on YouTube

Formula.Firewall Error in Power Query & Power BI: Rebuild This Data Combination Solved (MSPTDA 9.5)

Learn how to deal with Power Query Error: Formula.Firewall: Query references other queries or steps, so it may not directly access a data source. Please rebuild this data combination. Two solutions are presented in this video.
Download Files: Excel Start: https://ift.tt/2L7OwpO
Zipped Folder: https://ift.tt/2PShOvY
Download Excel FINISHED Files: https://ift.tt/2MsL7Hs
Download pdf Notes about Power Query: https://ift.tt/2wkNW2K
Assigned Homework – these are problems for you to practice your new M Code skills:
Download Excel File with Homework: https://ift.tt/2MmtxFf
Example of Finished Homework: https://ift.tt/2L7OxtS

Chris Webb’s blog about this topic: https://ift.tt/2NATkG3
Ken Puls blog about this topic: https://ift.tt/2PShRb8

Comprehensive Microsoft Power Tools for Data Analysis Class, BI 348, taught by Mike Girvin, Excel MVP and Highline College Professor.

View on YouTube