VBScript does not include any functions to left pad or right pad a string, so these two functions will enable you to do just that.

Function LPad(StringToPad, Length, CharacterToPad) Dim x : x = 0 If Length > Len(StringToPad) Then x = Length - len(StringToPad) LPad = String(x, CharacterToPad) & StringToPad End Function Function RPad(StringToPad, Length, CharacterToPad) Dim x : x = 0 If Length > Len(StringToPad) Then x = Length - len(StringToPad) RPad = StringToPad & String(x, CharacterToPad) End Function

#### Add a Leading Zero

Left pads the number four to a length of two with a zero:

`LPad("4", 2, "0")`

#### Add a Trailing Zero

Right pads the number four to a length of two with a zero:

`RPad("4", 2, "0")`

#### Left Pad with spaces

Left pads a string with spaces to a length of ten:

`LPad("Hello ", 10, " ")`

#### Right Pad with spaces

Right pads a string with spaces to a length of ten:

`RPad("hello", 10, " ")`

It is a shame there isn’t a native way to pad with VBScript. But these small functions make it simple. I’ve also written up how to do padding with Powershell, which makes things much easier.

## Leave a Reply