Search code examples
excelvba

Execute If/Else when selection made in a dropdown


I want:
If cell C26 contain YES then cells D26 and E26 are empty (and can be adjustable by writing own text).
If cell C26 contains NO, then write in cells D26 and E26 "N/A".

The YES and NO are chosen from a drop down list.

I tried:

=IF(EXACT(C26,"No"),"N/A","")

rough snip of excel

If the formula is in the cell it works, but I want to write text in the cell the formula is in, that's why I want to switch to VBA.


Solution

  • Use the Worksheet_Change event handler:

    Private Sub Worksheet_Change(ByVal Target As Range)
        If Intersect(Target, Me.Range("C26")) Is Nothing Then Exit Sub
        
        Select Case Me.Range("C26").Value
            Case "YES", vbNullString
                Me.Range("D26:E26").ClearContents
            Case "NO"
                Me.Range("D26:E26").Value = "N/A"
        End Select
    End Sub
    

    If you don't want anything to happen when C26 = "YES", then remove the "YES" from:

    Case "YES", vbNullString
    

    EDIT: For a multiple cell setup:

    Private Sub Worksheet_Change(ByVal Target As Range)
        Dim rng As Range
        Set rng = Intersect(Target, Me.Range("C26:C27")) ' Change C26:C27 as needed
    
        If rng Is Nothing Then Exit Sub
        
        On Error GoTo SafeExit
        Application.EnableEvents = False
    
        Dim cell As Range
        For Each cell in rng
            Select Case cell.Value
                Case "YES", vbNullString
                     cell.Offset(,1).Resize(,3).ClearContents
                Case "NO"
                     cell.Offset(,1).Resize(,3).Value = "N/A"
            End Select
        Next
    
    SafeExit:
        Application.EnableEvents = True
    End Sub