Select all text in textbox (VBA 2003)

User avatar
AlanMiller
BronzeLounger
Posts: 1545
Joined: 26 Jan 2010, 11:36
Location: Melbourne, Australia

Select all text in textbox (VBA 2003)

Post by AlanMiller »

I'm sure I use the following code successfully in earlier VBA, when the user entered a textbox:

Code: Select all

    With txtItem
        .SetFocus
        .SelStart = 0
        .SelLength = Len(.Text)
    End With
I can't recall which event I used, but it worked in selecting all the text. I can't seem to get it to work in a Word 2003 VBA userform though, no matter which event I choose. Any ideas please?

Alan

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

Re: Select all text in textbox (VBA 2003)

Post by HansV »

If you want this to happen when the user tabs into txtItem, you can use its Enter event:

Code: Select all

Private Sub txtItem_Enter()
  With Me.txtItem
    .SelStart = 0
    .SelLength = Len(.Text)
  End With
End Sub
If you also want this to happen when the user clicks in txtItem, you must user the MouseDown event:

Code: Select all

Private Sub txtItem_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
  With Me.txtItem
    .SelStart = 0
    .SelLength = Len(.Text)
  End With
End Sub
In both situations, you don't need to use SetFocus since the text box already has the focus.
Best wishes,
Hans

User avatar
AlanMiller
BronzeLounger
Posts: 1545
Joined: 26 Jan 2010, 11:36
Location: Melbourne, Australia

Re: Select all text in textbox (VBA 2003)

Post by AlanMiller »

Thanks Hans. You hit on it with the MouseDown event. I forgot the Enter event related specifically to tabbing in. The SetFocus was a bit of added desperation from failing to get it working :blush:

cheers
Alan

User avatar
Jan Karel Pieterse
Microsoft MVP
Posts: 656
Joined: 24 Jan 2010, 17:51
Status: Microsoft MVP
Location: Weert, The Netherlands

Re: Select all text in textbox (VBA 2003)

Post by Jan Karel Pieterse »

A textbox has a property called EnterFieldBehavior, which determines whether or not all text is selected when the textbox gains focus. Set it to 0 - fmEnterFieldBehaviorSelectAll to have it -well- select all.
Regards,

Jan Karel Pieterse
Excel MVP jkp-ads.com

User avatar
AlanMiller
BronzeLounger
Posts: 1545
Joined: 26 Jan 2010, 11:36
Location: Melbourne, Australia

Re: Select all text in textbox (VBA 2003)

Post by AlanMiller »

Jan Karel Pieterse wrote:A textbox has a property called EnterFieldBehavior, which determines whether or not all text is selected when the textbox gains focus. Set it to 0 - fmEnterFieldBehaviorSelectAll to have it -well- select all.
Yes, that's what one would logically expect, but unfortunately it doesn't work for all events... hence the workaround. As Hans says, if the user tabs to the control it works, but not if the text within is clicked with the mouse.

Alan