OzGrid

TextBox for Numbers Only

< Back to Search results

 Category: [Excel]  Demo Available 

TextBox for Numbers Only

 

Validating UserForm TextBox to Accept Only Numbers

Got any Excel/VBA Questions? Excel Help

Validating UserForm TextBox to Only Accept Numbers

If you are fairly comfortable with Excel VBA you will most likely want to design a UserForm to ensure correct use of your Spreadsheet. However, just placing some TextBoxes on a UserForm for users to enter data is not enough. For example, the TextBoxes may be intended to take only numeric data and not Text strings. To do this you can use some code as shown below.

Private Sub TextBox1_Change() 

    OnlyNumbers 

End Sub 

 

Private Sub TextBox2_Change() 

    OnlyNumbers 

End Sub 

 

Private Sub TextBox3_Change() 

    OnlyNumbers 

End Sub 

 

Private Sub OnlyNumbers()



    If TypeName(Me.ActiveControl) = "TextBox" Then

        With Me.ActiveControl

            If Not IsNumeric(.Value) And .Value <> vbNullString Then

                MsgBox "Sorry, only numbers allowed"

                .Value = vbNullString

            End If

        End With

    End If

    

End Sub 

As with any UserForm Control code, this code must reside in the Private Module of the UserForm Object

 

See also:

Index to Excel VBA Code
Excel Lookup nth Occurrence/Instance
Add Excel UDF/Custom Function to a Category & Add a Description
The Ultimate Excel Lookup Function
Update Links in Excel
Stop UserForm From Closing via X
Excel VBA Code For Excel UserForms & Controls

 

See also Index to Excel VBA Code and Index to Excel Freebies and Lesson 1 - Excel Fundamentals and Index to how to… providing a range of solutions.

 

Click here to visit our Free 24/7 Excel/VBA Help Forum where there are thousands of posts you can get information from, or you can join the Forum and post your own questions.


Gallery



stars (0 Reviews)