This code allows you to wrap the text in a label. Do not use this code in the Change event of the label. It will cause a bad result or possibly and error message. Be sure that the AutoResize property of the label is set to true. If you change the lines containing the width of the label the variable Break should be changed accordingly.
Usage: lblTheLabel.Text = WrapLabel(lblTheLabel)
Public Sub WrapLabel(Text As Label)
Dim XStr As String
Dim Break As Integer
Dim X As Integer
Dim Y As Integer
Dim Z As Integer
Break = 40 ' the width to break the text
With Text
If .Width > 2700 Then
Do Until .Width <= 2700
X = 0
Do Until X + Break >= Len(.Caption)
If .Width < 2700 Then Exit Do
Do Until InStr(Left(Right(.Caption, Len(.Caption) - X), Break), vbCr) = 0 And Left(Right(.Caption, Len(.Caption) - X), 1) <> vbLf
XStr = Left(Right(.Caption, Len(.Caption) - X - 1), Break)
X = X + 1
Loop
If X > 0 Then
XStr = Left(Right(.Caption, Len(.Caption) - X), Break)
Else
XStr = Left(.Caption, Break)
End If
XStr = Left(XStr, InStrRev(XStr, " "))
If XStr = "" Then
Y = 1
Do
Z = 15
XStr = Left(Right(.Caption, Len(.Caption) - X), Break / Y - Z)
Do Until InStr(Left(Right(.Caption, Len(.Caption) - X - Len(XStr)), 10), vbCr) = 0
Z = Z + Break / 1.5
XStr = Left(Right(.Caption, Len(.Caption) - X), Break / Y - Z)
Loop
If Right(Left(.Caption, Len(XStr) + 3), 3) = "-" & vbCrLf Then
Y = Y + 1
Else
Exit Do
End If
Y = Y + 1
Loop
XStr = XStr & "-" & vbCrLf
.Caption = Left(.Caption, X) & XStr & Right(.Caption, Len(.Caption) - Len(XStr) - X + 3)
Else
XStr = Left(XStr, Len(XStr) - 1) & vbCrLf
.Caption = Left(.Caption, X) & XStr & Right(.Caption, Len(.Caption) - Len(XStr) - X + 1)
End If
X = X + Len(XStr)
If .Width <= 2700 Then GoTo Done
Loop
If .Width <= 2700 Then GoTo Done
Break = Break - 15
Loop
Done:
End If
End With
End Sub
Comments