Optimized Word Wrap Function
Hello,
I have searched the internet for an optimized word wrap function and came with the following code by Carl Franklin which I cleaned up (renamed the variables etc...). However I noticed two problems
1) I don't like the "GoTo LoopHere" statement. Is there a way to eliminate that? I always read that using Goto is bad form.
2) If a word is longer then the intLength variable, that word is not cut in the middle and restarted on the next line as word wrap is done in MS Word. Which is better for the word to be cut onto two lines? Or leave it the way it is?
Finally is there a better way of word wrapping then this function?
Thanks for any assistance.
Code:
Private Function WordWrap(strFullText As String, intLength As Integer) As String
Dim intLen As Integer, intCr As Integer, intSpace As Integer
Dim strText As String, strNextLine As String
Dim blnDoneOnce As Boolean
intLength = intLength + 1
strFullText = Trim$(strFullText)
Do
intLen = Len(strNextLine)
intSpace = InStr(strFullText, " ")
intCr = InStr(strFullText, vbCr)
If intCr Then
If intLen + intCr <= intLength Then
strText = strText & strNextLine & Left$(strFullText, intCr)
strNextLine = ""
strFullText = Mid$(strFullText, intCr + 1)
GoTo LoopHere
End If
End If
If intSpace Then
If intLen + intSpace <= intLength Then
blnDoneOnce = True
strNextLine = strNextLine & Left$(strFullText, intSpace)
strFullText = Mid$(strFullText, intSpace + 1)
ElseIf intSpace > intLength Then
strText = strText & vbCrLf & Left$(strFullText, intLength)
strFullText = Mid$(strFullText, intLength + 1)
Else
strText = strText & strNextLine & vbCrLf
strNextLine = ""
End If
Else
If intLen Then
If intLen + Len(strFullText) > intLength Then
strText = strText & strNextLine & vbCrLf & strFullText & vbCrLf
Else
strText = strText & strNextLine & strFullText & vbCrLf
End If
Else
strText = strText & strFullText & vbCrLf
End If
Exit Do
End If
LoopHere:
Loop
WordWrap = strText
End Function
Re: Optimized Word Wrap Function
It could probably be rewritten using byte arrays instead of strings. I don't have time to do that but one major improvement you could make is use this string concatenation class.
strText = strText & ... is what's slowing it down, especially for large text.
Add this class module to your project and declare strText as New clsConcat. And replace the:
strText = strText &
lines with:
strText.SConcat ...
http://www.vbforums.com/attachment.p...6&d=1175915331
Re: Optimized Word Wrap Function
You realize that this only works for fixed-width fonts like Courier, right?
Re: Optimized Word Wrap Function
also i don't see why you think a long word would be split in the middle. Intelligent word-wraps split at hyphens or double-letters, or syllables, and add hyphens when they do split them. A long word might not meet any of these criteria and not get split at all.