I’m building a UserForm in Excel VBA for simple data entry (i.e. surveys). The surveys are in the basic “Strongly Disagree” to “Strongly Agree” format. Each respondent has 8 options per question (“1”-“5” for the agreement rankings, “99” for N/A, and “88” should the respondent choose not to answer). To improve the speed and accuracy of the data entry process, I need my UserForm to only allow only those integers in the textboxes.
I’ve messed around with KeyPress, but have run into some trouble with the double digit entries. Here’s what I had:
Private Sub textbox1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
Select Case KeyAscii
Case Asc("1") To Asc ("5")
Case Asc("88")
Case Asc("99")
Case Else
KeyAscii = 0
End Select
End Sub
This worked alright, except that it’s not perfect, in that it also allows invalid entries such as, “11” – “15”, “81” – “85”, and so forth. I’ve spent a good two weeks looking around the internet for something and haven’t found anything. Surely there is a simple way to validate these textboxes the way I’m asking, but I just can’t seem to figure it out. Any help would be greatly appreciated.
Just let me know if anyone needs more of the code. Thanks in advance for your help.
Just check the value after they leave the field
Here is a solution that utlizes the submit button to validate (commandbutton1), per your recent comments. In the click method it loops through the controls and checks to see if it is a textbox, if so it passes the textbox to be validated. If it fails validation it will set focus back to the control, you may wish to add a message box so the user knows that it failed.