Set Focus to last Character in Control


Question

I have been unable to figure a way of doing this without send keys (end). I would like to set through code the cursor to the position after the last character in a text control. I am using the On Change event to check the ASC values of the new character that has been added ( right(mycontrol,1) ). If it is not alphanumeric I delete it (after telling user it is an illegal char). I do this by taking the Left (length of value less one) of the text. The problem with this is that it puts the cursor at the beginning of the field and I would like it at the end to allow the user to continue with their data entry in that field. Anybody?

Answer

Sean,

Hope this code helps you:

Private Sub txtTest_Change()
  Dim txt As Access.TextBox

  Set txt = Me![txtTest]
  If Len(txt.Text) > 0 Then
    Select Case Right(txt.Text, 1)
    Case "0" To "9", "A" To "z":
    Case Else
       MsgBox "Bad char !", vbExclamation + vbOKOnly
       txt.Text = Left(txt.Text, Len(txt.Text) - 1)
       txt.SelStart = Len(txt.Text)
    End Select
  End If
End Sub

HTH,
Shamil


Copyright 1999-2008 by Shamil Salakhetdinov.  All rights reserved.