Search code examples
excelvbauserformsetfocus

How to select text in a textbox?


I have a userform with a textbox. I want to select the text within (highlight) after the keyDown event.

There are some restrictions to what the end user can enter. In case of wrong entry, a message would pop up, and the text in the textbox inviting the user to enter something should be selected.

I use the following code:

Me.txtbox_add_folder.SetFocus
Me.txtbox_add_folder.SelStart = 0
Me.txtbox_add_folder.SelLength = Len(Me.txtbox_add_folder.Text)

The setFocus doesn't work. It seems that it's because setFocus triggers a series of other events see this discussion.

The solution proposed in a different discussion is to include a DoCmd.CancelEvent or Cancel = True, so that the focus doesn't go to another control, but these commands don't work on Excel.


Solution

  • I found a solution finally. Actually the focus was lost automatically after the event, so to avoid that, one should turn off the TabStop parameter in properties.