Using event "On Change" to force uppercase in text box

darlingm

Registered User.
Local time
Today, 00:20
Joined
Feb 24, 2008
Messages
14
I have a text box that I want to be all uppercase, regardless of how the user types it in.

I searched the forums, and found methods to use the event "After Update" to handle this, such as:

Code:
Private Sub TextSomething_AfterUpdate()
   Me.TextSomething = UCase(Me.TextSomething)
End Sub

However, I think it would be more slick if it displayed the keys instantly as uppercase, like how professionally made non-Access applications do it.

I tried the code below, however the problem is that everytime a key is hit, the cursor is moved back to the beginning of the string so the user can't keep typing, and has to move the cursor to the end of the string. :(

Anyone have an idea on how to: (a) prevent the cursor from moving; (b) move the cursor back to where it was (not necessarily at the end, but where it was); or (c) do something else to accomplish immediate caps, rather than waiting for the After Update event?

I don't want to use an input mask for several reasons.

Code:
Private Sub TextSomething_Change()
   Static PreventRecursiveCall As Boolean

   If PreventRecursiveCall = True Then
      PreventRecursiveCall = False
      Exit Sub
   End If

   PreventRecursiveCall = True
   Me.Something.Text = UCast(Me.Something.Text)
End Sub

Note 1: Me.Something = UCast(Me.Something) didn't work, so I went with .Text in the _Change()

Note 2: Setting .Text to something appears to trigger the On Change event again, that's why there's a static boolean to prevent an infinite loop (well actually VBA seems to stop it after like 25 iterations or so.) I can't initialize PreventRecursiveCall to false in this function, and I'm currently taking advantage that Boolean's default to false in VBA, but I might later make it a global static and in the Open event initialize it there.
 
Set the form's Key Preview to Yes, then use the following code to alter the Keyascii value, I'ved used ActiveControl.Name here just to restrict this to a specific textbox.


Code:
Private Sub Form_KeyPress(KeyAscii As Integer)
    If ActiveControl.Name = "txtCaseMgr" Then
        KeyAscii = Asc(UCase(Chr(KeyAscii)))
    End If
End Sub
 
I'ved used ActiveControl.Name here just to restrict this to a specific textbox.
Actually it would be restricted to the text box with the KeyPress if you use the control's KeyPress event. You don't have to use the form event.
 
I use the Form event as I like to manage all the Keypresses I'm interested in, in the one sub.
 

Users who are viewing this thread

Back
Top Bottom