Visual Basic 6 function "wordwrap"

Go back

Below you'll find the source for the Visual Basic 6 function wordwrap.

Attribute VB_Name = "modWordwrap"
' This function is downloaded from:
' http://www.stefanthoolen.nl/archive/vb6-functions/
' 
' You may freely distribute this file but please leave all comments, including this one, in it.
' 
' @Author Stefan Thoolen <mail@stefanthoolen.nl>

Option Explicit

''
' This function wraps long lines to short ones
' Same syntax as the PHP function 'wordwrap'
' See also: http://www.php.net/manual/en/function.wordwrap.php
' @param    String  str         The string that needs to be wrapped
' @param    Integer Optional    The maximum characters on each line (default 75)
' @param    String  break       The break character (default CrLf)
' @param    Boolean cut         Do we simply cut or wrap on whitespaces (default False)
' @author   Stefan Thoolen <mail@stefanthoolen.nl>
Public Function wordwrap(str As String, Optional width As Integer, Optional break As String, Optional cut As Boolean)
    If Len(str) <= width Then wordwrap = str: Exit Function
    Dim b As String, c As String, i As Long, j As Long, k As Long, ret As String
    If width = 0 Then width = 75
    If break = "" Then break = vbCrLf
    If cut Then
        For i = 1 To Len(str)
            j = j + 1
            b = Mid(str, i, 1)
            If j = width Then j = 0: b = b & break
            ret = ret & b
        Next i
    Else
        For i = 1 To Len(str)
            b = Mid(str, i, 1)
            c = c & b
            If Len(c) >= width Then
                k = 0
                For j = 1 To Len(c)
                    If Mid(c, j, 1) = " " Then k = j
                Next j
                If k > 0 Then
                    ret = ret & RTrim(Left(c, k)) & break
                    c = Right(c, Len(c) - k)
                End If
            End If
        Next i
        ret = ret & c
    End If
    wordwrap = ret
End Function