Share via

Visual Basic in Excel

Anonymous
2025-01-07T10:43:01+00:00

I want to select more options from a drop-down list so I used Visual basic and add the following code in the module:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim Oldvalue As String
Dim Newvalue As String
Application.EnableEvents = True
On Error GoTo Exitsub
If Not Intersect(Target, Range("D3:D100")) Is Nothing Then
  If Target.SpecialCells(xlCellTypeAllValidation) Is Nothing Then
    GoTo Exitsub
  Else: If Target.Value = "" Then GoTo Exitsub Else
    Application.EnableEvents = False
    Newvalue = Target.Value
    Application.Undo
    Oldvalue = Target.Value
      If Oldvalue = "" Then
        Target.Value = Newvalue
      Else
        If InStr(1, Oldvalue, Newvalue) = 0 Then
            Target.Value = Oldvalue & vbNewLine & Newvalue
      Else:
        Target.Value = Oldvalue
      End If
    End If
  End If
End If
Application.EnableEvents = True
Exitsub:
Application.EnableEvents = True
End Sub

I then saved the file as an Excel Macro-Enabled Workbook. Still, that doesn't work, even though I added the right code.

Please advise,

Microsoft 365 and Office | Excel | For business | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

1 answer

Sort by: Most helpful
  1. HansV 462.6K Reputation points
    2025-01-07T10:48:32+00:00

    Did you create the code in the worksheet module of the relevant sheet, or in a standard module? It will only work in the worksheet module.

    If you did create it in the worksheet module:

    Are the cells with data validation of type List in D3:D100?

    Was this answer helpful?

    0 comments No comments