12

I'm trying to pad a string with 0's to the left.The length of the output string should be 7. Here's my code :

inputstr = "38"
in = string(7 - Len(inputStr),0) & inputStr
msgbox in

I'm getting error Expected Statement Please help me Thank You

Salman A
  • 262,204
  • 82
  • 430
  • 521
Yousuf Khan
  • 113
  • 1
  • 1
  • 6

4 Answers4

25

The following code will run 5% faster:

inputStr = "38"
result = Right("0000000" & inputStr, 7)

msgbox result
Andrej Kirejeŭ
  • 5,381
  • 2
  • 26
  • 31
  • 1
    But risks truncating and hardcodes width and filler. – Ekkehard.Horner Oct 23 '14 at 15:39
  • 2
    I just used a length provided in the question above. – Andrej Kirejeŭ Oct 23 '14 at 15:48
  • 3
    Is a great one-liner answer to the question and intuitively correct... exactly what I needed for this answer -- not a function definition, but something simple, /fastest possible/, and intuitive that I could just drop into my (>31-bit unsigned Hex function) code. Thanks Andrej. – Michael Back Nov 15 '15 at 20:17
17

This function will left-pad an input value to the given number of characters using the given padding character without truncating the input value:

Function LPad(s, l, c)
  Dim n : n = 0
  If l > Len(s) Then n = l - Len(s)
  LPad = String(n, c) & s
End Function

Output:

>>> WScript.Echo LPad(12345, 7, "0")
0012345
>>> WScript.Echo LPad(12345, 3, "0")
12345
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
6

in is a reserved word so can't be used as a variable name and you must pass a string "0" not an integer 0, so:

inputStr = "38"
result = string(7 - Len(inputStr), "0") & inputStr

msgbox result
Alex K.
  • 171,639
  • 30
  • 264
  • 288
1

Function:

Private Function LPad (str, pad, length)
    LPad = String(length - Len(str), pad) & str
End Function

Use:

LPad(12345, "0", 7)
Kempes
  • 11
  • 2