woensdag 22 oktober 2014

Excel: Data Validation And Stepped Choices With Names And VBA

In Excel you can validate a cell through Data => Data Validation.

We then will get this window:

At Allow we then can choose List and then at Source we pick the range where the data are.

Want we want to do here is select a continent first and then automatically restrict the choice in the next cel to countries from the specific continent.

In the example we see the data (in Dutch) which we are going to use in our example, A1:E6:

nigeriabraziliënieuw zeelandchinanederland
liberiaequadornieuw guineathailandpolen
sierra leoneperupakistanduitsland

We will use names here to make the stepped choices work.

We select A1:E6. We then choose the tab Formulas and  then Create From Selection. We'll get:

Here we check the upper box only. Then we click OK. We now created five names:


Next we create the name Werelddelen based on the range A1:E1.

Cell H1 in the same sheet we validate using a formula:


In cell I1 next to it we'll do the same using a different formula:


From this moment on the choice we make in cell H1 will determine the offered options of the list in cell I1.

There is still a problem left: in cell I1 the choice we made earlier is still there if we make another choice in cell H1. We need  VBA to correct this:.

Behind our sheet we put this code:

Private Sub Worksheet_Change(ByVal Target As Range)
    'MsgBox Target.Address
    If Target.Address = Range("H1").Address Then
        Range("I1").Value = ""
    End If
End Sub

Using VBA it is also possible to make the list in cell I1 drop down automatically when we make another choice in cel H1.

Private Sub Worksheet_SelectionChange(ByVal Target As Range) 
    On Error GoTo foutje: 
    If ActiveCell.Validation.Type > 0 Then Application.SendKeys ("%{down}") 

    Exit Sub 
End Sub

You can download the example Excelgetraptekeuze.xlsm through:

Een reactie plaatsen