Excel VBA Only Allow Numbers in TextBox Guide
In this article
To allow only numbers in an Excel VBA TextBox, you must use the KeyPress event and the Asc function to intercept keystrokes, canceling any character that does not fall within the numeric ASCII range (48 to 57). This ensures that users cannot type letters or special symbols into a field intended for digits, preventing runtime errors during calculations.
What You'll Need
- Microsoft Excel installed on a Windows PC.
- A UserForm created within the Visual Basic for Applications (VBA) editor.
- At least one TextBox control placed on that UserForm.
- Basic access to the VBA IDE (Alt + F11).
Step-by-Step
- Open the VBA Editor: Open your Excel workbook. Press
Alt + F11on your keyboard to launch the Visual Basic Editor. If you have not already created a form, go to the top menu and selectInsert > UserForm. - Add the TextBox: From the Toolbox window (if not visible, go to
View > Toolbox), click on the TextBox icon and draw a TextBox on your UserForm. By default, this will likely be namedTextBox1. Note the name of your TextBox in the Properties window, as you will need it for the code. - Access the Code Window: Right-click on the TextBox you just created and select
View Code. This opens the code module specifically tied to the UserForm. - Create the KeyPress Event: In the code window, you will see two dropdown menus at the top. In the left dropdown (the object dropdown), ensure your TextBox name (e.g.,
TextBox1) is selected. In the right dropdown (the procedure dropdown), selectKeyPress. VBA will automatically generate the event shell:Private Sub TextBox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger). - Insert the Validation Logic: Inside this subroutine, you need to check the ASCII value of the key being pressed. Copy and paste the following code:
If KeyAscii < 48 Or KeyAscii > 57 Then KeyAscii = 0. - Understand the Logic: The
KeyAsciivariable represents the character the user just typed. In the ASCII table, numbers 0 through 9 are represented by the values 48 through 57. By settingKeyAscii = 0, you are telling Excel to discard the keystroke entirely, meaning nothing appears in the box. - Allowing Backspaces: If you use the strict logic above, the user cannot use the Backspace key because the Backspace character has an ASCII value of 8. To fix this, modify the logic to:
If (KeyAscii < 48 Or KeyAscii > 57) And KeyAscii <> 8 Then KeyAscii = 0. - Testing the Form: Press
F5or click the green Play button on the toolbar to run the UserForm. Try typing letters, symbols, and numbers into the TextBox. You should find that only digits and the backspace key function correctly.
Common Mistakes
One of the most frequent errors is using the Change event instead of the KeyPress event. The Change event triggers after the character has already been entered into the TextBox. While you can use the Change event to strip out non-numeric characters using a loop or a Regular Expression, it creates a flickering effect where the letter appears for a millisecond and then vanishes. The KeyPress event is superior because it prevents the character from ever entering the control.
Another common mistake is forgetting to account for the Backspace key. If you simply restrict input to the 48-57 range, the user cannot correct a typo. This leads to a frustrating user experience where the only way to fix a mistake is to delete the entire contents of the box or close the form. Always include And KeyAscii <> 8 in your conditional statement.
Some developers attempt to use IsNumeric() within the KeyPress event. This is a logic error because IsNumeric checks a string, whereas KeyPress provides a single integer (the ASCII code). IsNumeric is better suited for the BeforeUpdate or Exit events, where you validate the final completed string rather than individual keystrokes.
Tips
Handling Decimals: If your TextBox needs to allow decimal numbers (floating point), you must allow the period character. The ASCII value for a period is 46. Update your code to: If (KeyAscii < 48 Or KeyAscii > 57) And KeyAscii <> 8 And KeyAscii <> 46 Then KeyAscii = 0. However, this allows the user to enter multiple periods (e.g., "12.34.56"), which is not a valid number.
Preventing Multiple Decimals: To ensure only one decimal point is entered, add a check to see if a period already exists in the TextBox: If KeyAscii = 46 And InStr(TextBox1.Text, ".") > 0 Then KeyAscii = 0. Place this line before your general numeric check.
Handling Negative Numbers: To allow negative numbers, you must permit the minus sign (ASCII value 45). Similar to the decimal point, you should ensure the minus sign can only appear at the very beginning of the string: If KeyAscii = 45 And TextBox1.SelStart > 0 Then KeyAscii = 0. This prevents users from typing "12-34".
Using a Class Module: If your UserForm has ten different TextBoxes that all need numeric-only input, writing the same KeyPress code ten times is inefficient. Instead, create a Class Module, define a public variable WithEvents txtNumeric As MSForms.TextBox, and put the logic there. You can then associate all your TextBoxes with this class upon form initialization, centralizing your validation logic in one place.
Troubleshooting
The code is not running: First, verify that the event name matches your TextBox name exactly. If your TextBox is named txtAge, the sub must be Private Sub txtAge_KeyPress(...). If you renamed the TextBox after writing the code, the event will no longer trigger because the name in the code does not match the object name.
Letters are still getting through: Check if you have other events (like Change or AfterUpdate) that are interfering with the input. Also, ensure you are using a UserForm TextBox. This method does not work for ActiveX TextBoxes placed directly on a worksheet in the same way; those may require different event handling or the use of Data Validation if a cell is used instead.
The form crashes when I type: This is rarely caused by the KeyPress logic itself, as it is very simple. Check for other code in your form that might be triggering on a change. If you have a Change event that performs a calculation based on the TextBox value, it might be crashing because it is trying to calculate while the TextBox is still empty or contains only a minus sign.
I cannot type anything at all: Ensure you haven't accidentally set the Enabled property of the TextBox to False or the Locked property to True in the Properties window. Also, double-check your logic operators; using Or where you should use And can lead to a condition that is always true, effectively blocking every single key pressed.
Frequently Asked Questions
Can I use this for cells on a worksheet instead of a UserForm?
No, the KeyPress event is specific to UserForm controls. For worksheet cells, use the Data Validation feature (Data tab > Data Validation > Allow: Whole Number) to restrict input without needing VBA.
Does this prevent users from pasting text into the box?
No. The KeyPress event only monitors keyboard typing. A user can still right-click and paste non-numeric text into the box. To prevent this, you should add a validation check in the Change event or the BeforeUpdate event to verify the final string is numeric.
How do I allow only a specific number of digits?
You can use the MaxLength property in the TextBox Properties window to set a hard limit on the number of characters. Alternatively, in the KeyPress event, you can add a condition: If Len(TextBox1.Text) >= 5 Then KeyAscii = 0 to stop input after 5 characters.
What is the difference between ASCII 48-57 and other numeric checks?
ASCII 48-57 refers specifically to the keyboard characters for 0-9. Other checks, like IsNumeric, evaluate the resulting string. The ASCII method is a "preventative" measure, while IsNumeric is a "detective" measure.
Will this work on Mac versions of Excel?
VBA UserForms have limited support on macOS. While basic events often work, the behavior of KeyAscii can occasionally differ. It is recommended to test the form thoroughly on a Mac to ensure the ASCII values are being captured correctly.
Can I allow only integers and no decimals?
Yes, the standard code provided in the step-by-step section (which only allows ASCII 48-57 and 8) specifically restricts the input to integers only, as it blocks the period (46) and comma (44) characters.