Just wondering, is there any equivalent in VBA to VB .NET\'s PadLeft and PadRight methods?
As of right now, whenever I want to take a string and make it a fixed leng
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)
I solved the problem by reassigning variable.
In my code I get data from workbook cell and limit it to 5 char (if necessary fill with enough 0..):
MB = Right(String(5, "0") & Worksheets("HOME").Range("b3"), 5)
MB = Right(MB, 5)
Merging the top two answers (thanks to LittleBobbyTables and Brad) and noting the helper function max, I would suggest:
Function PadLeft(ByVal text As Variant, ByVal totalLength As Integer, ByVal padCharacter As String) As String
PadLeft = Right(String(totalLength, padCharacter) & CStr(text), max(totalLength, Len(CStr(text))))
End Function
Function PadRight(ByVal text As Variant, ByVal totalLength As Integer, ByVal padCharacter As String) As String
PadRight = Left(CStr(text) & String(totalLength, padCharacter), max(totalLength, Len(CStr(text))))
End Function
Public Function max(ByVal x As Variant, ByVal y As Variant) As Variant
max = IIf(x > y, x, y)
End Function
totalLength might be better named minimumLength, since the entire original string is always returned, possibly causing the result to be longer than minimumLength.
Format("abc","!@@@@@@") ' width >= 6; pad right side with spaces
Format("abc","@@@@@@") ' width >= 6; pad left side with spaces
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 Function
Function 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")