Preselect text in a form

User avatar
Cah
3StarLounger
Posts: 293
Joined: 26 Mar 2010, 10:53

Preselect text in a form

Post by Cah »

Hello, is there anyway to preselect the text in a textbox (the contents are variable) so that all the text is highlighted and at the same time have the OK button as the default? That way if the user wants to change the text they can just start typing and if they are happy with it they can just press return to process the form. I tried this code:

Code: Select all

Private Sub UserForm_Initialize()

    With textboxExample
        .SelStart = 0
        .SelLength = Len(.Text)
    End With

End Sub
But the results are inconsistent. If I change the value of the text just before calling up the form then this doesn't work and the text isn't highlighted. Without changing the default text the text is highlighted. An other ways to preselect the text. If it helps the form only has one text box and an OK button. Thanks,

Chris

User avatar
HansV
Administrator
Posts: 78667
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Preselect text in a form

Post by HansV »

Set the Default property of the command button to True. (You still need to create an On Click event procedure for it to do anything).

You may have to set focus to the text box too:

Code: Select all

Private Sub UserForm_Initialize()
  With Me.TextBoxExample
    .Text = "Hello World"
    .SetFocus
    .SelStart = 0
    .SelLength = Len(.Text)
  End With
End Sub
Best wishes,
Hans

User avatar
jscher2000
2StarLounger
Posts: 148
Joined: 26 Dec 2010, 18:17

Re: Preselect text in a form

Post by jscher2000 »

Is this in Office VBA or a different user form library? In Word 2003, this seems to work:

Code: Select all

Private Sub CommandButton1_Click()
MsgBox "SelText=" & Me.TextBox1.SelText
Me.Hide
End Sub

Private Sub UserForm_Initialize()
With Me.TextBox1
    .Text = "hello"
    .SelStart = 0
    .SelLength = Len(.Text)
End With
Me.CommandButton1.SetFocus
End Sub
Edit: Setting default=true on the commandbutton and focus to the text makes more sense. Please ignore. :grin:
Cah wrote:But the results are inconsistent. If I change the value of the text just before calling up the form then this doesn't work and the text isn't highlighted.
If the form was initialized and hidden, you may need to move your code to the activate event.

User avatar
Cah
3StarLounger
Posts: 293
Joined: 26 Mar 2010, 10:53

Re: Preselect text in a form

Post by Cah »

jscher2000 wrote:If the form was initialized and hidden, you may need to move your code to the activate event.
Thanks, moving the code to the activate event did the trick.