Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Increment a number and respect leading zeros

Status
Not open for further replies.

russgreen

Programmer
Dec 7, 2002
86
GB
Hi there,

This, I know is simple but.....

I am doing this simple VBA macro to place numbers (with a prefix) into a Microstation drawing. The number increments by 1 everytime the text is placed.

I have a little function that returns an incremented number. When you pass in a number like IncrementNumber(1) it returns 2.

That's great.

But if you pass in IncrementNumber(001) then it will still return 2. I really want it to be able to return 002

Does anyone have a neat little function to increment a number by 1 while respecting the number of leading zeros (however many there are?)

Private Function IncrementNumber(ByVal sNumber As String) As String
Dim iTemp As Integer

iTemp = CInt(sNumber) + 1

IncrementNumber = CStr(iTemp)
End Function

TIA

Russ

Regards,
Russ

 
There's probably a better way of doing this but it works,

Code:
Private Function IncrementNumber(ByVal sNumber As String) As String
Dim iTemp As Integer
Dim x As Integer
Dim str As String

For x = 1 To Len(sNumber)
    If Mid$(sNumber, x, 1) = "0" Then
        str = str & "0"
    End If
Next
 
iTemp = CInt(sNumber) + 1
 
IncrementNumber = str & CStr(iTemp)
End Function

Regards,

Patrick
 
As an update, witht eh code above if you enter a number like 0010 it won't work, here's the revised edition...
Code:
Private Function IncrementNumber(ByVal sNumber As String) As String
Dim iTemp As Integer
Dim x As Integer
Dim str As String

For x = 1 To Len(sNumber)
    If Mid$(sNumber, x, 1) = "0" Then
        str = str & "0"
    Else
        Exit For
    End If
Next
 
iTemp = CInt(sNumber) + 1
 
IncrementNumber = str & CStr(iTemp)
End Function

Regards,

Patrick
 
russgreen said:
This, I know is simple but.....
yep, you said it

Code:
IncrementNumber = Format$(iTemp,string(len$(sNumber),"0")

I am sure you get the idea, but you might need to adjust for passing in "9"

Take Care

Matt
If at first you don't succeed, skydiving is not for you.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top