Search code examples
excelvbaformatuser-inputuserform

How to demand from User to type a five digit number only in UserForm?


I have code that need to be filled with data by user and that data should be only a five digit number or user should get a msgBox "Can only be numbers" or something like that.

If a user enters a five digit number in TextBox1 (UserForm) that value is going to Excel sheets in specific cells. That's the idea for code to do.

My code is checking if User type number in cell but not asking to enter format for example "00000".

User can type a three digit number and code will run.

Private Sub TextBox1_Change()

If Not IsNumeric(TextBox1.Value) = Format(TextBox1.Value, "") = True Or TextBox1.Value = vbNullString Then
    MsgBox "Invalid data type"

Else: TextBox1.Value = Format(TextBox1.Value, "")
    Sheets("POVRATNICE").Range("B2").Value = TextBox1.Value
    
End If

End Sub

Solution

  • you should consider adding "length of textbox1 does not equal 5 then..."

    If Not IsNumeric(TextBox1.Value) = Format(TextBox1.Value, "") = True Or TextBox1.Value = vbNullString Or len(TextBox1.value) <> 5 Then
    

    If the textbox is anything but 5 characters then you get the message...