Search code examples
excelvbainputbox

VBA Inbut box with loop


I have just started learning VBA (and coding in general) and I am faced with a problem to which I have not yet found a solution. I'd like to create an input box with a loop so that the output from the input box will be printed to separate cell. For example, I would like to write number "5" to the input box and the output will be printed to Cell "A1" and the next input, say number "9", will be printed to Cell "A2".

So far, I have managed to this and everything works fine except the last row as I don't know how to continue from here.

Private Sub CommandButton1_Click()
Dim myValue As Variant

myValue = InputBox("Please insert number")

Range("A1").Select
ActiveCell.Value = myValue

Range(ActiveCell) = Range(ActiveCell) + 1

End Sub

All help is appreciated


Solution

  • Try with below code

    Private Sub CommandButton1_Click()
        Dim myValue As Variant
        myValue = InputBox("Please insert number")
        Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1) = myValue
    End Sub
    

    EDIT #1: Updated the code as per the advice of user3598756

    Private Sub CommandButton1_Click()
        Dim myValue As Variant
        myValue = InputBox("Please insert number")
        If Range("A" & Range("A" & Rows.Count).End(xlUp).Row).Value = "" Then
            Range("A" & Range("A" & Rows.Count).End(xlUp).Row) = myValue
        Else
            Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1) = myValue
        End If
    End Sub