|
-
Apr 24th, 2024, 09:54 AM
#1
Thread Starter
Hyperactive Member
-
Apr 24th, 2024, 10:02 AM
#2
Thread Starter
Hyperactive Member
Re: VBA automatically adds a leading zero to a number stored as text
I am answering my own question. Apparently if I use Cstr instead of Format, that works. Strange... never had this issue before!
-
Apr 25th, 2024, 07:42 AM
#3
Re: VBA automatically adds a leading zero to a number stored as text
 Originally Posted by Chrissy
Strange... never had this issue before!
It's always the best to know how things work, usually means to find the root cause of any problem you meet.
What you have here is a String as a result of Cells(xRow, xCol) invocation. Then you call Format with this String as a parameter but Format expects a number so your String (in a Variant parameter) is cast to Double at some point inside Format code, then this Double is formatted and the result returned by Format is a String.
You "fixed" your code by substituting Format for CStr so now you call CStr on a String just to get a String. This is called no-op from "no operation" like "nothing happens here" and usually is completely redundant and dead code should be quickly removed during code reviews.
The moral of the story: Don't call Format *on Strings* if you don't want to format anything as it might change your input into so called "canonical representation" of the number.
cheers,
</wqw>
-
Apr 25th, 2024, 08:56 AM
#4
Thread Starter
Hyperactive Member
Re: VBA automatically adds a leading zero to a number stored as text
 Originally Posted by wqweto
It's always the best to know how things work, usually means to find the root cause of any problem you meet.
What you have here is a String as a result of Cells(xRow, xCol) invocation. Then you call Format with this String as a parameter but Format expects a number so your String (in a Variant parameter) is cast to Double at some point inside Format code, then this Double is formatted and the result returned by Format is a String.
You "fixed" your code by substituting Format for CStr so now you call CStr on a String just to get a String. This is called no-op from "no operation" like "nothing happens here" and usually is completely redundant and dead code should be quickly removed during code reviews.
The moral of the story: Don't call Format *on Strings* if you don't want to format anything as it might change your input into so called "canonical representation" of the number.
cheers,
</wqw>
That explains why it was adding the leading zero, thank you for the explanation! I guess I don't need Cstr() either.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|