Search code examples
excelvbalistboxuserform

Copy and delete selected listbox item


I have code that:

  1. UserForm1 Listbox 1 populates it's item from Worksheet1
  2. UserForm2 contains textboxes and a submit button
  3. When I select an item from UserForm1 ListBox1, it copies the values to UserForm2 Textboxes

I want, when I go into UserForm 2 and click the submit button, the row from Worksheet1 moved to Worksheet2

Below is the code within UserForm1 ListBox1

Private Sub UserForm1ListBox1_Click()
    With UserForm2
        .TextBox1 = ListBox1.Column(0)
        .TextBox2 = ListBox1.Column(1)
        .TextBox3 = ListBox1.Column(2)
        .TextBox4 = ListBox1.Column(3)
        .TextBox5 = ListBox1.Column(4)
    End With
End Sub

Below is the code within UserForm2 submit button. Getting error commented in the code.

Private Sub Userform2SubmitButton_Click() 
    Dim i As Long

    For i = UserForm1.ListBox1.ListCount - 1 To 0 Step -1
        If UserForm1.ListBox1.Selected(i) Then

            Worksheets("Worksheet1").Range("A" & i + 1). _
            Copy Worksheets("Worksheet2").Range("A" & Rows.Count).End(xlUp).Offset(0)

            If UserForm1.ListBox1.ListIndex >= 0 Then
            LastRow = Worksheets("Worksheet1").Cells(Rows.Count, "A").End(xlUp).Row

            Worksheets("Worksheet1").Range("A" & LastRow).Find(what:=UserForm1.ListBox1.Value, LookIn:=xlValues, LookAt:=xlWhole).Activate   '<------------------error here!
            Worksheets("Worksheet1").Rows(ActiveCell.Row).Delete

        End If
     End If
    Next i
End Sub

Solution

  • Something along these lines. Have left a few comments/queries in the code as not sure about a few things. Note how to handle the possibility of Find not finding anything.

    Private Sub Userform2SubmitButton_Click()
    
    Dim i As Long, r As Range, ws As Worksheet
    
    Set ws = Worksheets("Worksheet1")
    
    For i = UserForm1.ListBox1.ListCount - 1 To 0 Step -1
        If UserForm1.ListBox1.Selected(i) Then
            ws.Range("A" & i + 1).Copy _
                  Worksheets("Worksheet2").Range("A" & Rows.Count).End(xlUp).Offset(1) 'changed offset to 1 so as not to overwrite
            If UserForm1.ListBox1.ListIndex >= 0 Then
                LastRow = ws.Cells(Rows.Count, "A").End(xlUp).Row 'not sure what this is for
                Set r = ws.Cells.Find(what:=UserForm1.ListBox1.Value, LookIn:=xlValues, LookAt:=xlWhole)
                If Not r Is Nothing Then 'avoid error if nothing found
                    r.EntireRow.Delete
                End If
            End If
        End If
    Next i
    
    End Sub