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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Incrementing a variable and retaining the format

Status
Not open for further replies.

impulse24

IS-IT--Management
Jul 13, 2001
167
US
Hi,

I have a program that reads a number value for a text file, and then for each line in the text file the number value is incremented by one. The problem is that the number value is padded with zero's and changes for each different file. I am able to increment the value however the 0's are lost when doing so. How do I retain the format of the original value, without knowing how many zero's are padding the number? Below is a sample file, and my code

Sample File:
Test|037120001
Test|037120002

Dim strTmp() as string
Dim numval as string
Open sample file for Input As #1
Do Until EOF(1)
Line Input #1, Data
strTmp = Split(Data,"|")
numval = strTmp(1) + 1
Msgbox numval
Loop
Close #1

With the above code the first value that is returned is
37120002 when I need it to be the original value format
03712002. What am I doing wrong? I tried to set the variable as an integer or long datatype with the same results. Please help
 
You are implicitly converting the string to a number by adding 1 to it (how else would VB be able to do any math with it?), this is why the leading 0 is removed.

If you want to retain the format, you should measure the length of the string:

dim nLength as Integer.
nLength = len(strTemp(1)

Then convert it to a number (and better do it explicitly)and add 1:

dim lNr as Long
lNr = CLng(strTemp(1)) + 1

then use the Format function to create a string (with the right number of leading zeroes):

dim sVal as String
sVal = Format(lNr, String(nLength, "0"))


Now you'll have your number in the current format.


Greetings,
Rick
 
numbers don't have leading zeros, text strings that represent numbers can though. What you need to do is format the number as a string when outputting it.

Since the length of the string changes, get that first.
nLength = Len(strTmp(1))

Then format your number to that size
Msgbox Format(numval, String(nLength, "0"))
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top