Search code examples
vbaexcel-2013

Input box value insert in the next empty cell in row to the right


I am trying to add to the next empty cells to the right, the data from the user form text box, if data already exists. Meaning if "E1" is has date, add to "F1" and so on, but only is the range "E1:S1".

Here is a screenshot of the report:

enter image description here

And here is what I've got so far (but it stops as E1):

Private Sub CommandButton1_Click()

    If Range("E1") = "" Then Range("E1") = UserForm2.TextBox1.Value Else
    Range("E1").End(xlToRight) = UserForm2.TextBox1.Value
    If Range("E2") = "" Then Range("E2") = UserForm2.TextBox2.Value Else
    Range("E2").End(xlToRight) = UserForm2.TextBox2.Value
End Sub

Solution

  • The End(xlToRight is only going to the end of the populated cells not the next open one. You need to move one more column over after finding the last populated cell. Use Cells() and I prefere staring at the furthest column and coming back.

    Private Sub CommandButton1_Click()
    
        If Range("E1").Value = "" Then Range("E1").Value = UserForm2.TextBox1.Value Else
        Cells(1, Cells(1, Columns.Count).End(xlToLeft).Column + 1).Value = UserForm2.TextBox1.Value
        If Range("E2").Value = "" Then Range("E2").Value = UserForm2.TextBox2.Value Else
        Cells(2, Cells(2, Columns.Count).End(xlToLeft).Column + 1).Value = UserForm2.TextBox2.Value
    End Sub