Dynamic (Cascading) Dropdowns that reset on change
Dynamic dropdowns are a handy way to get your users to make choices based on what they’ve previously chosen, while steering them away from making invalid choices. Today we’re going to look at one that easily handles multiple levels, and we’ll take a look at what could go wrong. Let’s see one in action, shall we?
Earliglow? Never heard of it. Sounds delicious…I’ll have those, please.
There, all done. Pretty nifty eh…users only get to see valid choices depending on what they chose last. So users simply can’t screw up! Or can they?
[Evil user, determined to prove me wrong]: Wait a minute…I just remembered that mother expects me to eat my vegetables first, before I move on to dessert. So I better change that initial selection:
Damn…changing upstream dropdowns later on means those downstream choices can be flat out wrong! So how can we make this bulletproof?
Macros to the rescue
Now watch what happens when our user subsequently decides they better vege out first:
Ahh…look at that: the code realized that all those downstream choices are no longer valid. So it deleted them, and prompted the user to choose again. There. Now that IS bulletproof.
MEAT! Yummy. BURP!
What’s the recipe?
My approach draws on Roger Govier’s excellent sample file on the Contextures website. Be sure to check out that link to see Roger’s in-depth discussion of the formula magic behind this puppy…It’s genius.
In my Dynamic-Dependent-dropdowns-20140214, you’ll see that all the different categories used by the dropdowns are hosted in an Excel Table, that has the initial categories down the left hand side, and subsequent categories across the top:
Here’s the MainList formula:
…and here’s the SubList formula:
The SubList formula has a relative reference in it: whatever cell you use it in, it retrieves the value of the cell to the immediate left, and then it scans the column headers of our validations table (Table1) looking for the heading that matches that value. Once it’s found it, it simply uses the items listed underneath that heading.
Because this formula is relative, before you enter it into the Name Manager, you will need to first select cell C8, because the above relative formula refers to B8 – the cell to the left. (Note that it doesn’t matter what is in C8 or where your actual dropdown are…rather it’s just that the above formula happens to refer to B8, and because we want our formula to always reference the cell on the immediate left, then we’ve got to select the cell to the immediate right before we enter this relative formula into the Name Manager.
Also note that my version of Roger’s approach uses Excel Tables and the associated Structured References that Table functionality allows. My table is called Table1. Your validation lists MUST be held within an Excel Table (which requires Excel 2007 or greater) and you MUST change the Table1 references in the above formula to match the name of your table.
Excel Tables – known as ListObjects to VBA developers – were introduced in Excel 2007, and are a very powerful and simple way to store things like lists, chart data, and PivotTable data…especially if you might need to add more data to your spreadsheet at a later date, and want to avoid having to repoint all your formulas to include the additional data. If you’re not familiar with Excel Tables – or you don’t know what that Table1[#Headers] guff above means – then I strongly suggest you check out Chandoo’s Introduction to Structural References and this great video he did with MrExcel.
The beauty of Roger’s approach is that it can handle any number of cascading levels, provided all the category names are unique. All you need to do is simply add the new subcategories to the right hand side of our validations table (Table1).
Let’s add a further level that would give meat eaters some further choices relating to how their meat is prepared.
Now here’s the magic: as soon as we add another column to our input table and set it up with data validation – which I did simply by clicking on the bottom right corner of the cell with the word ‘Human’ and dragging it across – then Excel picks up on the fact that there’s a sub-subcategory, and serves it up to us. *BING!* Order up!
Add code, and stir-fry for 10 milliseconds
As mentioned earlier, in addition to Roger’s great method, I’ve written some code that clears out any downstream entries in the event that an upstream entry is changed. It’s in the sample workbook already, all set to go. But here’s the actual code, for you VBA nerds. (Special thanks to Gabor Madacs for some enhancement suggestions)
Option Explicit Const CHOOSE = "Choose…" Private Sub Worksheet_Change(ByVal Target As Range) On Error GoTo ErrorHandler Dim targetCell As Range Dim nextCell As Range Dim oldCalc As Excel.XlCalculation If Not Intersect(Target, [DataEntryTable]) Is Nothing Then If [Radio_Choice] = 1 Then With Application .EnableEvents = False .ScreenUpdating = False oldCalc = .Calculation .Calculation = xlCalculationManual End With For Each targetCell In Target 'Clear any cells that use 'SubList' to the right of targetCell in the current table. If targetCell.Column < (targetCell.ListObject.ListColumns.Count + targetCell.ListObject.Range.Column - 1) Then 'there are table cells to the right For Each nextCell In targetCell.Offset(, 1).Resize(, targetCell.ListObject.ListColumns.Count + targetCell.ListObject.Range.Column - targetCell.Column - 1) If HasValidationFormula(nextCell) Then If nextCell.Validation.Formula1 = "=SubList" Then nextCell.Value = "" End If Next nextCell End If 'Perform different action depeding on whether we're dealing with a 'MainList' dropdown ' or a 'SubList' dropdown If HasValidationFormula(targetCell) Then Select Case targetCell.Validation.Formula1 Case "=MainList" If targetCell.Value = "" Then targetCell.Value = CHOOSE ElseIf targetCell.Value = CHOOSE Then 'Do nothing. Else targetCell.Offset(, 1).Value = CHOOSE End If Case "=SubList" If targetCell.Value = "" Then targetCell.Value = CHOOSE ElseIf targetCell.Offset(, -1).Value = CHOOSE Then targetCell.Value = "" ElseIf targetCell.Value = CHOOSE Then 'Do nothing Else Set nextCell = targetCell.Offset(, 1) If HasValidationFormula(nextCell) Then If nextCell.Validation.Formula1 = "=SubList" Then nextCell.Value = CHOOSE End If End If End Select End If Next targetCell With Application .EnableEvents = True .ScreenUpdating = True .Calculation = oldCalc End With End If End If Exit Sub ErrorHandler: With Application .EnableEvents = True .ScreenUpdating = True If oldCalc <> 0 Then .Calculation = oldCalc End With MsgBox Err.Description, vbCritical, Name & ".Worksheet_Change()" End Sub Private Function HasValidationFormula(cell As Range) As Boolean On Error GoTo ValidationNotExistsError If cell.Validation.Formula1 <> "" Then HasValidationFormula = True Else HasValidationFormula = False End If Exit Function ValidationNotExistsError: HasValidationFormula = False End Function
Hungry for more?
Here’s some related Posts at Chandoo.org:
Download the file
To see how this is done, download this file and enable macros:
About the Author.
Jeff Weir – a local of Galactic North up there in Windy Wellington, New Zealand – is more volatile than INDIRECT and more random than RAND. In fact, his state of mind can be pretty much summed up by this:
That’s right, pure #VALUE!
Find out more at http:www.heavydutydecisions.co.nz
Introducing our Online Power BI Class:
Would you like to join me on a date with Power BI? In this comprehensive online class, learn all about Power BI so you can create beautiful, insightful & interactive reports. Join me and rest of the play mates for our first ever Power BI Play Date.Click here to know more and join us.
Leave a Reply
|Power Pivot course is now open, Please join to become awesome||Learn how to create these 11 amazing dashboards|