Search code examples
excelvbauserform

Excel VBA: Userform code replaces row content instead of adding a new one


I'm a beginner, learning to code in VBA and this is my first post. I've been struggling lately on how to get my UserForm to work.

This is the code for the "Add" button in my UserForm, when ever I would run that macro (by pressing the add button) it would take the top row of my sheet and replace the content of the cells.

What I'm trying to achieve is actually adding a new row to the sheet with all the info I inputted. It's been a few days that I'm struggling so that's why (after intensive google searches) I finally decide to ask you guys for some help :) Hope I was clear enough.

Have a nice day,

Dim L As Integer

If MsgBox("Are you sure to create a new row with those information ?", vbYesNo, "Confirmation") = vbYes Then L = Sheets("BDD").Range("A65536").End(xlUp).Row + 1 'Adding the new line to the sheet

 Range("B" & L).Value = CboResp.Text
 Range("C" & L).Value = CboStat.Text
 Range("D" & L).Value = CboNat.Text
 Range("E" & L).Value = CboPrio.Text
 Range("F" & L).Value = CboAff.Text
 Range("G" & L).Value = CboLea.Text
 Range("H" & L).Value = txtDateRD.Text
 Range("I" & L).Value = txtDateEnv.Text
 Range("J" & L).Value = CboIni.Text
 Range("K" & L).Value = CboISAV.Text
 Range("L" & L).Value = txtVin.Text
 Range("M" & L).Value = txtContrat.Text
 Range("N" & L).Value = txtClientFinal.Text
 Range("O" & L).Value = txtImmat.Text
 Range("P" & L).Value = txtNomCon.Text
 Range("Q" & L).Value = txtPrenomCon.Text
 Range("R" & L).Value = txtTelCon.Text
 Range("S" & L).Value = txtMotif.Text
 Range("T" & L).Value = txtDateRDV.Text
 Range("U" & L).Value = txtDateInter.Text
 Range("V" & L).Value = CboVH.Text
 Range("W" & L).Value = txtComment.Text
 Range("X" & L).Value = CboCon.Text

End If


Solution

  • This would be more robust:

    Dim L As Long
    
    If MsgBox("Are you sure to create a new row with those information ?", vbYesNo, "Confirmation") = vbYes Then
    
        With Sheets("BDD")
             L = .Range("A65536").End(xlUp).Row + 1 'Adding the new line to the sheet
    
             .Range("B" & L).Value = CboResp.Text
             .Range("C" & L).Value = CboStat.Text
             .Range("D" & L).Value = CboNat.Text
             .Range("E" & L).Value = CboPrio.Text
             .Range("F" & L).Value = CboAff.Text
             .Range("G" & L).Value = CboLea.Text
              'etc etc
         End with
    End If
    

    Assuming there is always a value in ColA for each row of added data.