Hi Rod,
[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. [/quote]
It is ... because, in my opinion, it's not the right solution of the problem.
[quote user="RodWing"]Every time a user enters a key stroke into the TextBox the input is validated.[/quote]
It's a root of the problem: In GUI, there are (at least) two levels of "validation":
- The first can be imagined as a filter what even (key press, mouse clicks...) will be passed to GUI controls (form, text box...). Anything not related to a business logic should not pass (maybe something like very special Gandalf telling "You shall not pass"? ;-).
- The second validation level is "business logic", in other words data in allowed form or value are evaluated in terms of possible consequences to an internal logic.
From this perspective, if discussing about "integer number text box", it has to be implemented at the first level (as soon as possible).
[quote user="RodWing"]If you want more of a real-time validation use the Exit event [/quote]
Oh, nooo ;-) ... Exit is not real time validation at all ;-)
What about this code:
' Can be used to switch off Ctrl+V and INSERT + SHIFT Private Sub TB_CustomRed_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer) If (Shift = 2 And KeyCode = vbKeyV) Or (Shift = 1 And KeyCode = vbKeyInsert) Then KeyCode = 0 End If End Sub ' Allow to enter numbers only Private Sub TB_CustomRed_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger) Select Case KeyAscii Case vbKey0 To vbKey9, vbKeyLeft, vbKeyRight, vbKeyTab Case Else KeyAscii = 0 End Select End Sub
It protects a particular text box to be pasted any value (probably it can be enhanced to allow to paste integer values from clipboard, but I was too lazy to think about it ;-) and it filters everything except numeric keys and arrows, so to change event always only integer numbers (or empty text box content) is passed.
In languages like C# (WinForms or WPF) better solution is to inherit a proper control (TextBox) and to add necessary filters and checks to it, so it can be used in any form without any other code. It how GUI libraries like Telerik, DevExpress or ComponentOne are developed. Unfortunately it's not possible to inherit a control directly in VBA.
With regards,
Jan