Borisw37
Borisw37

Reputation: 759

VBA remove ListBox row on click

I have a list box not linked to any range.

I want to click on a row and remove it. If I step through the code below, the ListBox1_Click() function ends up being called twice for some reason and the application produces an "Unspecified Error" on the second run

My entire code:

Private Sub ListBox1_Click()
    ListBox1.RemoveItem (ListBox1.ListIndex)
End Sub

Private Sub UserForm_Initialize()
    For i = 0 To 10
        ListBox1.AddItem ("A" & Str(i))
    Next i
End Sub

Upvotes: 0

Views: 1606

Answers (1)

Vityata
Vityata

Reputation: 43575

If you make a button about it, then this solution would be quite ok there:

Private Sub CommandButton1_Click()

    Dim cnt     As Long
    For cnt = Me.ListBox1.ListCount - 1 To 0 Step -1
        If Me.ListBox1.Selected(cnt) Then
            Me.ListBox1.RemoveItem cnt
            Exit Sub
        End If
    Next cnt

End Sub

Upvotes: 1

Related Questions