Aligning strings within a fixed width
2009-06-05 Strings 0 268
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