mardi 6 novembre 2018

How can I use VBA to enable multiple Excel drop down lists that enter a different value from what the user selects?

This is my first attempt at using VBA. I'm adapting a script offered by Contextures.com that goes with "Excel drop down list automatically changes product name to code" (https://www.youtube.com/watch?v=uLJEMnIT0zM). I've successfully created on dropdown that adds the ID that is associated with the parameter type that a user selected (e.g. when the user selects "Chlorophyll" from a dropdown on the data entry Excel worksheet, Excel enters the ID number associated with that parameter name in the same cell, based on a list contained in a table on a second worksheet). However, when I try to add more options, the script stops working. The adapted code adds two ElseIf statements for other column dropdowns. When the script runs it doesn't report any errors. Also, oddly, it occasionally works on the first go. The code is below.

Many thanks in advance for your assistance.


Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

If Target.Cells.Count > 1 Then GoTo exitHandler

If Target.Column = 2 Then
    If Target.Value = "" Then GoTo exitHandler
    Application.EnableEvents = False
    Target.Value = Worksheets("CHLA Maps").Range("B1") _
        .Offset(Application.WorksheetFunction _
        .Match(Target.Value, Worksheets("CHLA 
Maps").Range("paramTypeList"), 0), 0)
Exit Sub

ElseIf Target.Column = 3 Then
    If Target.Value = "" Then GoTo exitHandler
    Application.EnableEvents = False
    Target.Value = Worksheets("CHLA Maps").Range("F1") _
        .Offset(Application.WorksheetFunction _
        .Match(Target.Value, Worksheets("CHLA 
Maps").Range("labMethodList"), 0), 0)
    Exit Sub    
ElseIf Target.Column = 4 Then
    If Target.Value = "" Then GoTo exitHandler
    Application.EnableEvents = False
    Target.Value = Worksheets("CHLA Maps").Range("J1") _
        .Offset(Application.WorksheetFunction _
        .Match(Target.Value, Worksheets("CHLA 
Maps").Range("parameterQCCodeList"), 0), 0)
    Exit Sub
Else
    Exit Sub   
End If
exitHandler:
    Application.EnableEvents = True
    Exit Sub
End Sub

Aucun commentaire:

Enregistrer un commentaire