WrapCode


Description:
These functions word wrap code passed to them. Since these codes wrap the code somewhat intelligently, by putting an underscore at the end of lines, and trying to break apart long strings, it's ideal for use on code before sending it via mail, or posting it. Note: This code uses the clsStringCollection class, it's available under the Strings->Split on my sample code page.
 
Code:
Private Function WrapCode(ByVal sCode As String) As String
    
    Dim sc As New clsStringCollection
    Dim vLine As Variant

    sc.SplitInto sCode, vbNewLine
    For Each vLine In sc
        WrapCode = WrapCode & WrapCodeLine(CStr(vLine)) & vbNewLine
    Next

End Function

Private Function WrapCodeLine(sLine As String) As String

    If Len(sLine) >= 75 Then
        Dim sOut As String
        Dim nSpacePos As Long
        Dim nTab As Long
        Dim bQuote As Boolean
        Dim i As Long
        Dim j As Long
        
        nTab = 0
        
        While Mid(sLine, nTab + 1, 1) = " "
            nTab = nTab + 1
        Wend
        
        While Len(sLine) >= 73 - (nTab + 3)
            nSpacePos = 73
            Do Until Mid(sLine, nSpacePos, 1) = " "
                nSpacePos = nSpacePos - 1
            Loop
            
            If bQuote Then
                j = nTab + 7
            Else
                j = 1
            End If
            
            For i = j To nSpacePos
                If Mid(sLine, i, 1) = Chr(34) Then
                    bQuote = Not bQuote
                End If
            Next
            
            If bQuote Then
                sOut = sOut & Mid(sLine, 1, nSpacePos) & Chr(34) & " _" _
                   & vbNewLine

                sLine = Space(nTab + 3) & "& " & Chr(34) & Mid(sLine, _
                   nSpacePos + 1)

            Else
                sOut = sOut & Mid(sLine, 1, nSpacePos) & "_" & vbNewLine
                sLine = Space(nTab + 3) & Mid(sLine, nSpacePos + 1)
            End If
        Wend
        
        sOut = sOut & sLine & vbNewLine
        WrapCodeLine = sOut
        
    Else
        WrapCodeLine = sLine
    End If

End Function

 
Sample Usage:
 
    Dim sCode As String
    sCode = WrapCode(Clipboard.GetText)
    Clipboard.Clear
    Clipboard.SetText sCode