When you use the
TextWidth method on very large
Strings, either a maximum value is returned, or the following error message is generated:
Run-time error '6':
Overflow
To determine which behavior is seen and at what
String length it occurs, change the
FontSize,
FontName, or
ScaleMode property.
To work around this problem, write a routine to recursively call
TextWidth on smaller portions of the large
String and return the sum. For example, you can call the following function instead of using
TextWidth directly:
Function fTextWidth(sInString As String) As Long
If Len(sInString) > 500 Then
fTextWidth = Printer.TextWidth(Left(sInString, 500)) + _
fTextWidth(Right(sInString, Len(sInString) - 500))
Else
fTextWidth = fTextWidth + Printer.TextWidth(sInString)
End If
End Function
If you are not using
TextWidth with the
Printer object, substitute the correct object for
Printer. This function handles large or small
Strings without problems.
You can use the
GetTextExtentPoint32 function to retrieve the text height and width, but this is also limited under Microsoft Windows 95 and Microsoft Windows 98. The function that is provided in the "Resolution" section should always work.
Steps to Reproduce Behavior
- Create a new Standard EXE project. Form1 is created by default.
- Add the following code to the General Declarations section of Form1:
Private Sub Form_Click()
Dim TWidth As Long, THeight As Long
Dim Msg As String
Me.FontName = "MS Sans Serif" ' Default
Me.FontSize = 8.25 ' Default
Debug.Print Me.FontName, Me.FontSize
Msg = String(4682, "A") ' 4681 works
THeight = TextHeight(Msg)
TWidth = TextWidth(Msg) ' May cause Overflow error.
Debug.Print "TextHeight = "; THeight, "TextWidth = "; TWidth
End Sub
- If the Immediate window is not open, press the CTRL+G key combination to open it.
- Run the project, and click on the form. Notice that run-time error 6 occurs.
- Stop the project, change the number of characters in the String function from 4682 to 4681, and repeat the test. The call succeeds and the following information appears in the Immediate window:
MS Sans Serif 8.25
TextHeight = 195 TextWidth = 491505
For some fonts and sizes on Windows 95, Windows 98, and Microsoft Windows Millennium Edition (Me),
TextWidth appears to return a maximum value without raising an error. For other fonts and sizes, the "Overflow" error is raised.