PDA

View Full Version : Solved: Find width of text



nst1107
12-22-2008, 04:53 PM
For a while now, to figure out how wide to make textboxes or what the maxlength should be, I've been filling my textboxes with the failsafe capital "W" to see what the maximum possible width of the text could be. But, now I'm trying to develop a scrolling marquee textbox and I'd like to programmatically find how wide a string is so I will know how much of it will fit in my textbox without wrapping. Is there a way to do this?

rbrhodes
12-22-2008, 05:54 PM
Hi Nate,

Perhaps post a small example of your workbook..

GTO
12-22-2008, 06:03 PM
Greetings Nate,

Not sure if this will help, but here's a little 'cheat' to approximate the string width. I would note that this does not return the actual width of the text, as there's an internal margin on top of the text width, but you might be able to get a good enough approximation using a hidden textbox.

Option Explicit
Dim strText As String

'// Note: Add two text boxes to a userform, named: "txtHidden" and "txtVisible"//

Private Sub UserForm_Initialize()

strText = "Here's a line of text that I want to know the width of..."

'// In the Initialize event, assign the text to a hidden text box that autosizes... //
With txtHidden
.AutoSize = True
.Visible = False
.Text = strText
End With

End Sub

Private Sub UserForm_Activate()

With txtVisible
.AutoSize = False
.Visible = True
'// ...then set the width of the visible text box to the width of the hidden //
'// one, or if it's too wide, some other width of your choosing. //
.Width = Application.WorksheetFunction.Min(txtHidden.Width, 200)

.Text = strText
End With

MsgBox "Hidden Text Box Width:" & vbTab & txtHidden.Width & vbCrLf & _
"Visible Text Box Width:" & vbTab & txtVisible.Width

End Sub

BTW, for the "scrolling marquee" - have you considered using a label instead?

Hope this helps,

Mark

nst1107
12-22-2008, 09:13 PM
Thanks, Mark. That's a good idea.
Yes, I've thought about using a label. The problem with a label is that it doesn't display spaces at the end of lines, so the scrolling text jerks at the end of each word.