• Status: Solved
• Priority: Medium
• Security: Public
• Views: 4025

# 000 Zero Padding in .vbs

Hi guys. I am looking for a function that puts 3 zero pads in front of numbers.

e.g

Thank you
0
New_Alex
• 4
1 Solution

Try the following:

Chris
``````Function zeropad(str)

zeropad = (Right("000" & str, 3))

End Function
``````
1

Commented:
Just one correction:
``````Function zeropad(str)
if Len(str) <= 3 then
zeropad = (Right("000" & str, 3))
else
End Function
``````
0

Adding a little flexibility but more work when calling:

The modified function takes two parameters, first the number to prepend, and secondly how many zeroes to be prepennded, (number of characters to be returned in fact).

Chris
``````MsgBox ZeroPad(22, 3)

ZeroPad = Right(replace(Space(charcount), " ", "0") & num, charCount)
End function
``````
0

Adding checks for non numeric and more than the stipulated number of characters then ...

Chris
``````MsgBox ZeroPad("0022", 3)

If isnumeric(num) Then
If Len(num) > charcount Then
Else
ZeroPad = Right(replace(Space(charcount), " ", "0") & num, charCount)
End if
Else
End if
End Function
``````
0

Basically the same but making the three character limit hard so that the call is 'easier' but keeping the simplicity to change the length of the string easily at the code level (within the function)

Chris
``````MsgBox ZeroPad("a2")

Const charCount = 3

If isnumeric(num) Then
If Len(num) > charcount Then
Else
ZeroPad = Right(replace(Space(charcount), " ", "0") & num, charCount)
End if
Else
End If

End Function
``````
0

Author Commented:
Thank you sir
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.