• Skip to main content
  • Skip to header right navigation
  • Skip to site footer

My Online Training Hub

Learn Dashboards, Excel, Power BI, Power Query, Power Pivot

  • Courses
  • Pricing
    • Free Courses
    • Power BI Course
    • Excel Power Query Course
    • Power Pivot and DAX Course
    • Excel Dashboard Course
    • Excel PivotTable Course – Quick Start
    • Advanced Excel Formulas Course
    • Excel Expert Advanced Excel Training
    • Excel Tables Course
    • Excel, Word, Outlook
    • Financial Modelling Course
    • Excel PivotTable Course
    • Excel for Customer Service Professionals
    • Multi-User Pricing
  • Resources
    • Free Downloads
    • Excel Functions Explained
    • Excel Formulas
    • Excel Add-ins
    • IF Function
      • Excel IF Statement Explained
      • Excel IF AND OR Functions
      • IF Formula Builder
    • Time & Dates in Excel
      • Excel Date & Time
      • Calculating Time in Excel
      • Excel Time Calculation Tricks
      • Excel Date and Time Formatting
    • Excel Keyboard Shortcuts
    • Excel Custom Number Format Guide
    • Pivot Tables Guide
    • VLOOKUP Guide
    • ALT Codes
    • Excel VBA & Macros
    • Excel User Forms
    • VBA String Functions
  • Members
    • Login
  • Blog
  • Excel Webinars
  • Excel Forum
    • Register as Forum Member

Clear Downstream Dependent Data Validation Lists

You are here: Home / Excel VBA / Clear Downstream Dependent Data Validation Lists
Clearing Downstream Dependent Data Validation Lists
August 25, 2016 by Philip Treacy

Following on from Mynda's post last week on Dependent Data Validation, I've written a little VBA that enhances the functionality.

What this code does is to clear any cells dependent on the value of another data validation list. I'll call these downstream cells.

So if I change the Country, I'm going to clear the values in the State/County and City cells. This doesn't normally happen in Excel, it just leaves the State/County and City as they were, and leaves it up to you to change them.

The first thing we need to do is convert the data into a table, with the name LocationsTable.

excel table

This allows us (amongst other things), to use structured references to refer to the table, or parts of it.

Detecting a Change

To detect a change in one of the cells using data validation, I'm going to use the Worksheet_Change event, and so the code will be in the Sheet1(Multi DV) module in the workbook you can download below.

Worksheet_Change is triggered when any change is made on the sheet, so my code must check that the cell being changed is one that I want to run the code for, and ignore other changes.

I need to check that the cell being changed is in either the Country column or the State/County column of the table. I do this using structured references to those columns, and checking to see if the Target (the changed cell) intersects those columns.


    If Intersect(Target, [LocationsTable[Country]]) Is Nothing And Intersect(Target, [LocationsTable[State/County]]) Is Nothing Then
    
        Exit Sub
      
    End If

If you click on a cell that uses data validation, and then click on the same value that is already in the cell, Excel sees this as a change.

So if the country is Australia, and you then click on the cell and select Australia, you haven't actually changed the country but Excel still executes the Worksheet_Change event.

We need to take this into account so we don't clear the State/County and City when the Country hasn't changed.

When a change is made we store the new value in a variable NewValue. Then we call Application.Undo to undo that change. Our cell now contains whatever value was there before we changed it.

Now we compare the NewValue and the old value, if they are different then a change has been made and the code can continue running, otherwise we can exit the code.


    NewValue = Target.Value
    Application.Undo
    
    ' If the old value is different to the new value
    '
    If Target.Value <> NewValue Then
    
        ' Assign the Newvalue to the changed cell
        '
        ' More code goes here
        '

Clearing the Downstream Cells

Once we know a change has happened, the code uses OFFSET to clear the cells downstream.


If Not Intersect(Target, [LocationsTable[Country]]) Is Nothing Then
        
   ' Clear the two downstream cells which are
   ' in the State/Country and City columns
   '
   Target.Offset(, 1).ClearContents
   Target.Offset(, 2).ClearContents
           
   Else
        
   ' Otherwise just clear one downstream cell
   ' which is in the City column
   '
   Target.Offset(, 1).ClearContents
            
End If

When you change the Country, the State/County and City are cleared, and the next cell that needs to be completed is selected.

If you just change the State/County, the City is cleared.

clearing downstream dependent data validation lists

If you wanted to, you could add some conditional formatting to highlight the blank cells that need to be filled in.

Get the Code

Enter your email address below to download the sample workbook.

By submitting your email address you agree that we can email you our Excel newsletter.
Please enter a valid email address.

Download the workbook with the code for you to check out.

Clearing Downstream Dependent Data Validation Lists

More Excel VBA Posts

automating and emailing pivot table reports

Automating and Emailing Pivot Table Reports

Automate the creation and distribution of pivot table reports with some VBA. Send reports to multiple email recipients using Outlook.
Checking values in range objects with vba

Checking Values in Range Objects With VBA

Use built in tools or your own code to examine the values contained within Range objects in VBA. Sample code to download.
Static variables in VBA

Static Variables in VBA

Variables normally cease to exist once your Sub or Function has ended. But Static Variables allow you to preserve values after your code has finished.
save chart as image

Save Chart as Image

List all the charts in your workbook then select the ones you want to save as either PNG or JPG. Sample workbook and code to download
Excel Status Bar

Excel Status Bar

Use the Excel Status Bar to send messages to your users and to show a progress bar for your VBA code
Progress Bar for Excel VBA

Excel Progress Bar for VBA

Create your own progress bar for VBA in Excel. Use it to show that your code is still running, and how long before it finishes.
error handling in vba

Error Handling in VBA

Understand how Excel VBA generates errors, how to control what Excel does when an error occurs, and how to write your own error handling routines.
Finding File Metadata Using FileSystemObject

Finding File Meta Data Using FileSystemObject

Find file meta data like the creation date, last modified date and file size using Windows FileSystemObject in Excel VBA
Automatically Add Items to Data Validation List

Automatically Add Items to Data Validation List

Automatically Add Items to Data Validation List by typing in the new data. Then sort the source list for bonus points
Calculate end of period dates in Excel

Excel End of Period Dates

Calculating Excel End of Period Dates can be tricky if you don't use standard month ends. Here is a formula and UDF that solves the problem.

More Excel VBA Posts

Display All Matches from Search in Userform ListBox

Display All Matches from Search in Userform ListBox

Search a range for all partial and full matches of a string, and display matching records (entire rows) in a userform listbox. Sample code and userform.
animating excel charts

Animating Excel Charts

Use animation correctly to enhance the story your data is telling. Don't animate your chart just for some eye candy. Sample code and workbook to download.
dynamic data validation lists in userforms

Dynamic Data Validation Lists in Userforms

Data validation lists using the same source that are dynamically modified to prevent the same choice being made in each list.
show report filter pages for power pivot pivottables

Show Report Filter Pages for Power Pivot PivotTables

PivotTables created from Power Pivot can't use the 'Show Report Filter Pages' option. But this piece of VBA allows you to do just that.
charting real time data in excel

Charting Real Time Data in Excel

Receive data in real time and chart the data as it arrives. Can be used to chart things like stock prices or sensor readings. Sample code and workbook
select multiple items from drop down data validation list

Select Multiple Items from Drop Down (Data Validation) List

Choose multiple items from a data validation (drop down) list and store them all in the same cell. Sample workbook with working VBA.
Excel Calendar (Date Picker) to Use in Worksheets and Userforms

Multi-Language Excel Calendar (Date Picker) for Worksheets and Userforms

Easy to use, highly customizable and multi-language. This date picker is implemented as a userform that is simple to integrate into your workbook.
automating and emailing pivot table reports

Automating and Emailing Pivot Table Reports

Automate the creation and distribution of pivot table reports with some VBA. Send reports to multiple email recipients using Outlook.
search for data with userform

Searching for Data With a User Form

Search a list of records (like a table) using a user form, and then populate the fields of the search form when the record is found.
Checking values in range objects with vba

Checking Values in Range Objects With VBA

Use built in tools or your own code to examine the values contained within Range objects in VBA. Sample code to download.
Category: Excel VBATag: Excel VBA
Previous Post:Excel Dependent Data ValidationExcel Dependent Data Validation
Next Post:Excel Table Running Total Formula

Reader Interactions

Comments

  1. Ravi Shankar

    September 24, 2020 at 12:27 am

    I am getting Runtime error if this code is used with data validation for data entry in first cell through dependent list. Let me explain. If I type anything in the first cell apart from what is there in the drop down list, the data validation setting of error message set by me is triggered. Then if I try to undo then VBA run time error 1004 msg comes up which directs to Application.Undo at Line 38 of your original code. I can make out the error in VBA is because the error msg of data validation is not captured by it.
    Can you please tell how to handle the error in VBA.
    Thank.

    Reply
    • Philip Treacy

      September 24, 2020 at 9:05 am

      Hi Ravi,

      Why are you typing into a DV cell? If you do type in something that isn’t in the list, the error alert message should pop up and when you acknowledge that, the typed value in the cell should be cleared.

      I can’t reproduce your error. Please start a topic on the forum and attach your file so we can debug it.

      Regards

      Phil

      Reply
  2. Tuan Kriel

    August 26, 2019 at 8:00 am

    Thanks for this neat procedure.
    Would you please help me with the code to add a condition before the clear contents instruction?
    I would like to test if the current downstream value is available in the array for the parent value.
    If it is, then do not clear contents else do clear contents.
    ex. Parent=168, array for 168 =(37.61; 43.37; 49.13; 54.86)
    Parent=219, array for 219 =(43.37; 49.13; 54.86)
    So if 168 gets replace by 219 only clear the child if it is 37.61 because the array for 219 does not contain the value 37.61

    Reply
    • Catalin Bombea

      August 27, 2019 at 2:40 pm

      Hi Tuan,
      You can simply loop through the initial array and check if the items are in the new array.
      Application.Match should be enough:
      application.match(37.61, array(43.37, 37.61, 49.13, 54.86),0) will return the position of the item if there is a match, or “Error 2042” if there is no match.

      InitialArray=ParentArray
      NewArray=NewParentArray
      Dim Counter as Long
      For i=0 to Ubound(initialArray)
      If IsNumeric(Application.match(InitialArray(i),NewParentArray,0)) then
      Redim Preserve FinalArray(0 to Counter)
      FinalArray(Counter)=InitialArray(i)
      Counter=Counter+1
      Next


      At the end of the loop, you will have a FinalArray where all the items from InitialArray can be found in NewParentArray. Note that not only the InitialArray can contain items that cannot be found in NewParentArray, also the NewParentArray an contain items not in the InitialArray, this case is not handled in code as there is no specification of what should happen for this case.

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Current ye@r *

Leave this field empty

Sidebar

More results...

Shopping Cart

mynda treacy microsoft mvpHi, I'm Mynda Treacy and I run MOTH with my husband, Phil. Through our blog, webinars, YouTube channel and courses we hope we can help you learn Excel, Power Pivot and DAX, Power Query, Power BI, and Excel Dashboards.

Subscribe to Our Newsletter

Receive weekly tutorials on Excel, Power Query, Power Pivot, Power BI and More.

We respect your email privacy

Guides and Resources

  • Excel Keyboard Shortcuts
  • Excel Functions
  • Excel Formulas
  • Excel Custom Number Formatting
  • ALT Codes
  • Pivot Tables
  • VLOOKUP
  • VBA
  • Excel Userforms
  • Free Downloads

239 Excel Keyboard Shortcuts

Download Free PDF

Free Webinars

Excel Dashboards Webinar

Watch our free webinars and learn to create Interactive Dashboard Reports in Excel or Power BI

Click Here to Watch Now
  • Excel
  • Excel Charts
  • Excel Dashboard
  • Excel Formulas
  • Excel PivotTables
  • Excel Shortcuts
  • Excel VBA
  • General Tips
  • Online Training
  • Outlook
  • Power Apps
  • Power Automate
  • Power BI
  • Power Pivot
  • Power Query
 
  • About My Online Training Hub
  • Contact
  • Disclosure Statement
  • Frequently Asked Questions
  • Guarantee
  • Privacy Policy
  • Terms & Conditions
  • Testimonials
  • Become an Affiliate

Copyright © 2023 · My Online Training Hub · All Rights Reserved

Microsoft and the Microsoft Office logo are trademarks or registered trademarks of Microsoft Corporation in the United States and/or other countries. Product names, logos, brands, and other trademarks featured or referred to within this website are the property of their respective trademark holders.

Download A Free Copy of 100 Excel Tips & Tricks

excel tips and tricks ebook

We respect your privacy. We won’t spam you.

x