Search code examples
excelvbalistboxuserform

Delete a selected row from list boxes in Userform


I have two list boxes in my Userform. The first one is lstBox1 and the other lstBox2 with sheets "PUB1" and "PUB2" respectively. I tried creating a command button that can delete a selected row from any of the list boxes as well as in the sheet and shift up the cell row so that there won't be a blank row.

I used the following lines of code to initiate it for one of the listboxes and it worked perfectly but don't know how to modify it to work for the other listbox under the same procedure.

Private Sub cmdDelete_Click()

Dim i As Integer

For i=0 To Range ("A50").End(x1Up).Row-1

 If lstBox1.Selected(i) Then

   Rows(i).Select

   Selection.Delete

  End If

Next i

End Sub

Solution

  • Something like this:

    Private Sub cmdDelete_Click()
    
    With Worksheets("PUB1")
    Dim i As Long
    
    For i = 1 To .Range("A50").End(xlUp).row
    
     If lstBox1.Selected(i) Then
    
       .Rows(i).Delete
    
     End If
    
    Next i
    End With
    
    With Worksheets("PUB2")
    
    For i = 1 To .Range("A50").End(xlUp).row
    
     If lstBox1.Selected(i) Then
    
       .Rows(i).Delete
    
     End If
    
    Next i
    
    End With
    
    End Sub