Here is a system I use. It evaluates each key stroke as the user types it in. If the key stroke is a number then nothing happens, but if the keystroke is a letter or it will remove give an error message and remove the keystroke.
I have created an example code for a UserFrom with two textboxes...you can incorporate into your code.
To test create a UserForm with two textboxes named TextBox1 and TextBox2 and copy and paste the following code into it.
Option Explicit
Public EnableEvents As Boolean
Public NUMvalues As String, BxStr As String, LPos As Integer, LChar As String
Private Sub UserForm_Activate()
NUMvalues = "0123456789."
EnableEvents = True
End Sub
Private Sub TextBox1_Change() 'rename with your textbox name
BxStr = TextBox1.Text 'rename with your textbox name
If EnableEvents = True And BxStr <> "" Then
For LPos = 1 To Len(BxStr)
LChar = Mid(BxStr, LPos, 1)
If InStr(NUMvalues, LChar) = 0 Then
MsgBox "Only numbers allowed!", vbCritical
RemoveBdCharacter TextBox1 'rename with your textbox name
End If
Next
Else
EnableEvents = True
Exit Sub
End If
End Sub
Private Sub TextBox2_Change() 'rename with your textbox name
BxStr = TextBox2.Text 'rename with your textbox name
If EnableEvents = True And BxStr <> "" Then
For LPos = 1 To Len(BxStr)
LChar = Mid(BxStr, LPos, 1)
If InStr(NUMvalues, LChar) = 0 Then
MsgBox "Only numbers allowed!", vbCritical
RemoveBdCharacter TextBox2 'rename with your textbox name
End If
Next
Else
EnableEvents = True
Exit Sub
End If
End Sub
Private Sub RemoveBdCharacter(Bx As Variant)
BxStr = Left(BxStr, Len(BxStr) - 1)
EnableEvents = False
Bx.Text = BxStr
End Sub
Bookmarks