Any method equivalent to PadLeft/PadRight? Any method equivalent to PadLeft/PadRight? vba vba

Any method equivalent to PadLeft/PadRight?


I don't believe there are any explicit PADLEFT or PADRIGHT functions, but you can use a combination of SPACE and LEFT or RIGHT to prepend spaces to your string, and then grab the right X number of characters.

PADLEFT

strOrdNo = RIGHT(Space(8) & strOrdNo, 8)

If you want a character instead of spaces, you can use STRING instead of space (the example below left-pads with X):

strOrdNo = RIGHT(String(8, "X") & strOrdNo, 8)

PADRIGHT

strOrdNo = LEFT(strOrdNo & Space(8), 8)strOrdNo = LEFT(strOrdNo & String(8, "X"), 8)


You could use these. Put them in a public module

'NB Fails if input string is longer than the total length

Function PadLeft(text As Variant, totalLength As Integer, padCharacter As String) As String    PadLeft = String(totalLength - Len(CStr(text)), padCharacter) & CStr(text)End FunctionFunction PadRight(text As Variant, totalLength As Integer, padCharacter As String) As String    PadRight = CStr(text) & String(totalLength - Len(CStr(text)), padCharacter)End Function


Since we generally pad on the left side, the Format() function is shorter, simpler:

Format(number, "    ")Format(number, "00")