Warning: Undefined array key "HTTPS" in /customers/a/2/3/co93ul71s/webroots/r1107763/data/commonfunctions.php on line 287 Warning: Cannot modify header information - headers already sent by (output started at /customers/a/2/3/co93ul71s/webroots/r1107763/data/commonfunctions.php:287) in /customers/a/2/3/co93ul71s/webroots/r1107763/index.php on line 60 Erlandsen Data Consulting

Aligning strings within a fixed width

 2009-06-05    Strings    0    138

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