Tuesday 12 April 2011

Validate numeric form fields in VBA

To help users enter the correct information every time they use a VBA form we can apply some validation checks. VBA_logo
In today’s example I have a field called ‘productID.text’ that will always be a number. To ensure that no other types of characters are input, you can use the following code.
Private Sub productID_Change()

If IsNumeric(productID.Text) = False Then
MsgBox "The product ID must be a number"
productID.Text = ""
End If

End Sub
The code is applied to the change event of the field and makes sure it only receives numbers. If an illegal character is entered it pops up a message asking for the correct input and then clears the field ready for the next attempt.

No comments:

Post a Comment