CajunCenturion, I would do this in the Validation event and not the lost focus, change NumValue to a long, and use the IsNumeric function and not the Val function (only works if a decimal is in US format - for example, German format for .22 is ,22 so the Val will always return 0 there)
The best way I have found to do this is to add code in the keypress event of the text box:
You will need to check the KeyAscii for the values
vbKeyBack, vbKeyClear, vbKey0 to vbKey9, 45 for a minus sign, 44 for a comma, and 46 for a dot.
If it is none of these then set KeyAscii = 0 to cancel input.
Then check for IsNumeric in case more than one dot, comma or minus is entered:
Private Sub TextBox1_KeyPress(KeyAscii As Integer)
Select Case KeyAscii
Case vbKeyBack,vbKeyClear,45,44,46
Case vbKey0 to vbKey9
Case else
KeyAscii = 0
End Select
If Not IsNumeric(TextBox1.Text & Chr$(KeyAscii) then KeyAscii =0
End IF
End Sub
Add an additional check in the Validation event in case something went through:
Private Sub TextBox1_Validate(Cancel As Boolean)
If Not IsNumeric(TextBox1.Text) Then
'Error
MsgBox "Enter a Number"
TextBox1.SelStart = 0
TextBox1.SelLength = Len(TextBox1.Text)
Else
'In case more than 1 period is entered
TextBox1.Text = CDbl(TextBox1.Text)
End If
End Sub
I would create 2 functions out of all this so you do not have to repeat so much code everywhere (pass the KeyAscii ByRef,and the current TextBox Text ByVal.