20

I need to keep leading zeros on a list of numbers. The numbers are added like this (in a loop, but this is just an example using the (1, 1):

Set cel = Sheet.worksh.Cells(1, 1)
cel.ColumnWidth = 10
cel.Value = e.Name
cel.NumberFormat = "0000"

Where e.Name is the number, something like "0720". This displays on the worksheet just fine, but if I do something like this:

Msgbox Sheet.worksh.Cells(1, 1).Value

I get "720". I need it to be "0720", I know I could check using Len() and add the zeros that way, but I was wondering if there was a more direct approach with the Range object that would do this for me.

4 Answers 4

28

You are confusing a number with its textual representation.

You want the .Text property, not .Value, but then, you might have problems with it.

2
  • 9
    Careful with the text property. If the cell looks like this "####" that's what it is going to shoot back to you. It's safer to use Lance Roberts' method. Just a warning from experience.
    – Jon49
    Aug 3, 2011 at 22:46
  • If the circumstances allow you could add Columns("A:A").EntireColumn.AutoFit before calling .Text method on a cell.
    – IGRACH
    Sep 27, 2018 at 14:22
15

Use This:

Msgbox Format(Sheet.worksh.Cells(1,1).Value, "0000")
8

Even better, if you're not sure what the format is:

Msgbox Format(Sheet.worksh.Cells(1,1).Value, Sheet.worksh.Cells(1,1).NumberFormat)

3
  • This doesn't work as expected if the NumberFormat is General--when calling Format("397","General") you get "Ge0eral" as your result.
    – nvuono
    Jun 5, 2013 at 20:48
  • Is the problem that 397 is provided to Format() as text, not a number? Aug 25, 2013 at 17:30
  • 1
    @nvuono Just add an if statement for General (also, "Ge0eral"? You sure you didn't spell it wrong?)
    – user 88 91
    Jul 11, 2022 at 6:22
0

A little late to the party, but you could always try calling up the value and number format separately, like this:

Msgbox Application.WorksheetFunction.Text(Sheet.worksh.Cells(1, 1).Value, Sheet.worksh.Cells(1, 1).NumberFormat)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.