Search code examples
excelvbauserform

VBA to deselect items in userform listbox in a certain condition


I am using below code to let the user select items from the list while filling up the userform.

However when user select other, I want to deselect all items from the same listbox if he has selected any other than the "Other" item.

Below is the code, I am trying, however I don't know how I can deselect all items in userform if the User selects "Other" item in the listbox.

    For x = 0 To Me.LBX2.ListCount - 1
        If Me.LBX2.Selected(x) Then
            If Me.LBX2.List(x) = "Other" Then
                Me.LBX2.Selected(x) = False      '---This doesn't Deselect the items, not sure why-----
                If myVar1 = "" Then
                    myVar1 = Me.LBX2.List(x, 0)
                Else
                    myVar1 = myVar1 & vbLf & Me.LBX2.List(x, 0)
                End If
            End If
        End If
    Next x

Solution

  • With multiple selects the Click event is not available and using the Change event requires some logic to avoid an endless loop.

    Option Explicit
    
    Public EnableEvents As Boolean
    
    Private Sub ListBox1_change()
        If Not Me.EnableEvents Then Exit Sub
        
        Dim isOther As Boolean, i As Long, n As Long
        Dim var1 As String
        
        With ListBox1
            n = .ListIndex
            If n < 0 Then Exit Sub
            If .List(n) = "Other" Then
                isOther = True
                var1 = .List(n)
            End If
    
            Me.EnableEvents = False
            For i = 0 To .ListCount - 1
                If isOther Then
                   If i <> n Then .Selected(i) = False
                ElseIf .List(i) = "Other" Then
                   .Selected(i) = False
                ElseIf .Selected(i) Then
                    If Len(var1) Then var1 = var1 & vbLf
                    var1 = var1 & .List(i)
                End If
            Next
            Me.EnableEvents = True
        End With
        MsgBox var1
    
    End Sub
    
    Private Sub UserForm_Initialize()
        EnableEvents = True
    End Sub