Search code examples
excelvbadelete-row

Is there any way to delete selected item from listbox using Delete key?


I want to delete selected item from list box when Delete key is pressed. Actually in my userform I have a listbox which shows data from a worksheet and I have a "Delete" command button that deletes entire matching row from worksheet and then listbox updates. But I wanted to do same thing using physical Delete key of keyboard. I searched a lot on internet but couldn't find anything.


Solution

  • Try this

    Private Sub ListBox1_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
        
        If KeyCode = 46 Then
            With Me.ListBox1
                If .ListIndex <> -1 Then
                    If MsgBox("Delete current item?" & vbCrLf & .Value, vbYesNo + vbExclamation, "Delete entry") = vbYes Then
                        .RemoveItem (.ListIndex)
                    End If
                End If
            End With
        End If
        
    End Sub