0

I have values of 120, 136, 7120, 72136. The maximum string length should be 5, how do I go about making 120 "00120" and 136 "00136" etc?

Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
Valwrie
  • 133
  • 6
  • 1
    Single line will work in VBA `Range("A1").Value = "'" & Format(Range("A1").Value, "00000")` and `=TEXT(A1,"00000")` in Excel – Mikku Jun 24 '19 at 07:12

5 Answers5

3

Single line will work

  • VBA

Range("A1").Value = "'" & Format(Range("A1").Value, "00000")

  • Excel

=TEXT(A1,"00000")

Mikku
  • 6,538
  • 3
  • 15
  • 38
1

In your simple case you can try something simple like this:

Sub FiveCharString()

    Dim myStr As String

    myStr = "136"

    If Len(myStr) = 2 Then
        myStr = "000" & myStr
    ElseIf Len(myStr) = 3 Then
        myStr = "00" & myStr
    ElseIf Len(myStr) = 4 Then
        myStr = "0" & myStr
    End If

    Debug.Print myStr

End Sub

Returns 00136.

Dean
  • 2,326
  • 3
  • 13
  • 32
1
Function FillWithZero(number as long, digitCount as long) as string
     FillWithZero = Right(String(digitCount , "0") & number , digitCount)
End Function
FunThomas
  • 23,043
  • 3
  • 18
  • 34
1

Use a custom number format in your cells.
See Using a custom number format to display leading zeros
or Keeping leading zeros and large numbers

Or .NumberFormat = "00000" on your range.

I don't recommend to convert it into a string (unless it is something like a serial number that is not treated as an actual number).

Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
1

A simpler version compared to Dean's

Sub StrLength()
Dim i As Long, str As String

str = "136"
i = Len(str)

StrLength = String(ExpectedLength - Len(str), "0") & str

End Sub

Small subroutines as these can easily be used as Functions, where you call the function in a regular sub. For example, when you are looping through a range of cells:

Function StrLength(str As String, ExpectedLength As Long) As String
Dim i As Long

i = Len(str)

StrLength = String(ExpectedLength - Len(str), "0") & str

End Function


Sub Test()
Dim c As Range

For each c In ThisWorkbook.Sheets(1).Range("A1:B200")
    If Len(c.Value) < 5 Then c.Value = StrLength(Str:=c.Value, ExpectedLength:=5)
Next c

End Sub
Tim Stack
  • 3,209
  • 3
  • 18
  • 39
  • Note that this is the slowest idea you can have and will convert the number into a (mabye) usless string (no calculations with this anymore). Also you might want to have a look into `String(ExpectedLength - Len(str), "0")` to get rid of your loops. – Pᴇʜ Jun 24 '19 at 07:23
  • @Pᴇʜ noted and edited! – Tim Stack Jun 24 '19 at 07:40