Here is my code for doing exactly what you are asking.
I have defined the independent column as a named range called Major_Category
and set the drop down validation to a data list. I then have several other data lists that are named cat_subItems
. So, for your example the major category would have items
then I defined to more lists called
which would contain the names of the fruits or vegetables. Then based on the major category selection the Worksheet_change event will change the drop down validation in the next column over to either cat_fruit
or cat_vegetable
.
Note: This code does not play nice if you are using excel's protect worksheet.
See this question for dealing with Excel's worksheet/book protection.
Public Sub Worksheet_Change(ByVal target As Range)
On Error GoTo ErrHandler:
Dim VRange As Range, cell As Range
Dim msg As String
Dim validateCode As Variant
Dim modCell As Range
Set VRange = Range("Major_Category")
If Intersect(VRange, target) Is Nothing Then Exit Sub
For Each cell In Intersect(VRange, target)
b = cell.Value
curRow = target.Row
Set modCell = cell.Offset(0, 1) 'cell to modify the validation'
If Not (b = "") Then
modCell.Validation.Delete
modCell.Validation.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
'sets the validation formula to the list/range name'
xlBetween, Formula1:="=cat_" & b
modCell.Validation.IgnoreBlank = True
modCell.Validation.InCellDropdown = True
modCell.Validation.InputTitle = ""
modCell.Validation.ErrorTitle = ""
modCell.Validation.ErrorMessage = ""
modCell.Validation.ShowInput = True
modCell.Validation.ShowError = True
End If
Next cell
Cleanup:
Exit Sub
ErrHandler:
MsgBox Err, vbOKOnly, "Error Occurred"
Resume Cleanup:
End Sub