Interesting discussion guys, good to listen to different viewpoints.
[quote user="RodWing"]I have found that using the Change event of a TextBox control to validate an entry is quite annoying to a user. Every time a user enters a key stroke into the TextBox the input is validated. It doesn't allow for a user to backspace to correct an error they know they made without being reminded of their mistake.
Most of the VBA applications I write have some sort of dialog with an OK or Apply command button. I only validate their entries when they click on one of those buttons. If you want more of a real-time validation use the Exit event to make them tab out of the text box or click another control prior to doing the validation.[/quote]
Hi Rod,
Personally I'm not keen on button to validate the values though I do have a button which applies these values to back to an array but my preference is real-time checking/prevention as I'm not a fan of returning to a control to fix an incorrect value. What I currently have is no longer a message box that appears (unless either of the 3 text boxes are left empty) but instead I simply prevent the user from making a mistake in the first place which I think is a little more elegant.
Private Sub ValidateRGB(ByVal tBox As TextBox) Dim lRGB_Max As Long Dim lNumber As Long lRGB_Max = 255 With tBox If .Value <> vbNullString Then If IsNumeric(.Value) Then lNumber = CLng(.Value) Debug.Print lNumber If Val(.Value) > lRGB_Max Then .Value = Left(.Value, Len(.Value) - 1) Else .Value = lNumber End If Else .Value = Left(.Value, Len(.Value) - 1) End If Else MsgBox "Enter a number between 0 and 255" End If End With End Sub
I did attempt using the _Exit event however for some reason the SetFocus method wouldn't allow me to tab out of a TextBox (which contained an incorrect value) and then automatically return to it; instead the focus remained on adjacent TextBox that tab had moved the focus to. As such I stuck with the _Change event and I'm quite happy with how its working.