Excel VBA - Append string with "0"'s

Im trying to make a function to append a number with 0's, which I know cant work as an interger seeing as 00000 will recognize as 0, so trying to put it as a string.

I have two problems with my code:-
    Dim endRule As String
    endRule = Int("0")
    
    While Len(Str(startRule)) < 7
        startRule = Str(startRule & "0")
    Wend

Open in new window


1 - On first run startRule becomes " 0" (space at the front of the string).
2 - the "0" is never appended to the string, it always is " 0" (which the unknown space from issue #1).

My code runs great if it starts with a number apart from 0.

Does anyone have any suggestions?

Thank you
tonelm54Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

MacroShadowCommented:
Why use a custom function, use the built-in Format() function.
Format("0", "0000000")

Open in new window

0
Rgonzo1971Commented:
Hi,

in your example you define endRule but not StartRule

myString = "1"
myNewString =Left(myString & "0000000";7)

'or

myInt = 1
myNewString =Left(Format(myInt, "0") & "0000000";7)

Regards
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
tonelm54Author Commented:
Good afternoon,
MacroShadow: Using the format fills the wrong way, for example if run for the number 1, it becomes "0000001" instead of "1000000", I could use StrReverse, so for example:-
startRule = StrReverse(Format(startRule, "0000000"))

Open in new window

Which seems to work ok, but seems a bit of a hack :-S, but Ill go with it.

Rgonzo1971: Works as well, thank you
0
Rgonzo1971Commented:
Attention

if you number is bigger than 9 with your hacked code you will get a wrong answer

with 12 you get
2100000

Regards
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Excel

From novice to tech pro — start learning today.

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.