How to allow only numbers to be input in text box?
In Excel, we can apply the Data Validation function to allow only numbers to be entered into cells, but, sometimes, I want only numbers to be typed into a textbox as well as in cells. How to accept only numbers in a textbox in Excel?
The following VBA code can help you to enter numbers, period (.) and a negative sign only into a textbox, please do as this:
1. Create a textbox by clicking Developer > Insert > Text Box (ActiveX Control), and then draw a textbox as you need, see screenshot:
2. Then right click the textbox and select View Code from context menu to open the Microsoft Visual Basic for Applications window, and then replace the original code with the following VBA code into the blank module:
VBA code: Allow only numbers to be input into the textbox:
Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger) If KeyAscii > Asc("9") Or KeyAscii < Asc("0") Then If KeyAscii = Asc("-") Then If InStr(1, Me.TextBox1.Text, "-") > 0 Or _ Me.TextBox1.SelStart > 0 Then KeyAscii = 0 ElseIf KeyAscii = Asc(".") Then If InStr(1, Me.TextBox1.Text, ".") > 0 Then KeyAscii = 0 Else KeyAscii = 0 End If End If End Sub
3. Then save and close the code window, and exit the Design Mode, now, only numbers, period symbol and negative sign can be entered into the textbox, see screenshot: