Getting the value of text selected in a text box.

ChrisOswald

Active Member
Joined
Jan 19, 2010
Messages
454
Hi,

Does anybody know if it's possible to return the text in a textbox control that is selected? the closest I've come is this code:
Code:
Private Sub Command24_Click()
    Dim myCntl As Control
    Set myCntl = Me.txtBody
    myCntl.SetFocus
    MsgBox (myCntl.SelText)
End Sub
which puts the entirety of the contents of me.txtbody in the msgbox.
 

Excel Facts

Workdays for a market open Mon, Wed, Friday?
Yes! Use "0101011" for the weekend argument in NETWORKDAYS.INTL or WORKDAY.INTL. The 7 digits start on Monday. 1 means it is a weekend.
If you can specify the name explicitly without moving back, you can get it with:
Code:
Private Sub Command24_Click()
    MsgBox Me.txtBody.SelText)
End Sub
it will work. But the minute you set focus, it is lost. So, you would need to save that value to a variable in the Lost Focus event of the text boxes so that you can grab it directly.
Code:
' in the General Declarations Section of the form
Private strSelText As String

and then in the LostFocus event of each text box you will possibly want this from:
Code:
Private Sub txtBody_LostFocus()
   strSelText = Me.txtBody.SelText
End Sub

So then you can get it from your command button:
Code:
Private Sub Command24_Click()
       MsgBox strSelText
End Sub
 
Upvote 0
Thanks Bob.

This doesn't work entirely correctly on my computer (Access 2007) -- the text is being truncated to the first 128 characters.:confused: It does work correctly on a coworkers computer (Access 2003).

Any Ideas?

edit: the original code snippet also was truncating to 128 characters.
 
Last edited:
Upvote 0
Not sure - I somewhat vaguely have this idea that there was a bug in 2007 which was associated with something of this nature but I just can't remember.
 
Upvote 0

Forum statistics

Threads
1,224,586
Messages
6,179,710
Members
452,939
Latest member
WCrawford

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top