Aligning strings within a fixed width

 2009-06-05    Strings    0    97

With the functions below you can align a string (left, center or right) within a fixed width, this might be useful when you e.g. create reports with fix-width column formats.

Function AlignLeft(varItem As Variant, intWidth As Integer) As String
Dim strResult As String, i As Integer
    strResult = CStr(varItem)
    i = intWidth - Len(strResult)
    If i > 0 Then
        strResult = strResult & Space(i)
    End If
    If Len(strResult) > intWidth Then
        strResult = Left$(strResult, intWidth)
    End If
    AlignLeft = strResult
End Function

Function AlignCenter(varItem As Variant, intWidth As Integer) As String
Dim strResult As String, i As Integer
    strResult = CStr(varItem)
    i = intWidth \ 2 - Len(strResult) \ 2
    If i > 0 Then
        strResult = Space(i) & strResult
    End If
    If Len(strResult) > intWidth Then
        strResult = Left$(strResult, intWidth)
    End If
    AlignCenter = strResult
End Function

Function AlignRight(varItem As Variant, intWidth As Integer) As String
Dim strResult As String, i As Integer
    strResult = CStr(varItem)
    i = intWidth - Len(strResult)
    If i > 0 Then
        strResult = Space(i) & strResult
    End If
    AlignRight = strResult
End Function


Leave a comment:

Your comment will only be published after it has been moderated and found spam free.
Your e-mail address will only be used to display your Gravatar.