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

Loop Through String Until I Don't Hit a Zero

Status
Not open for further replies.

Fattire

Technical User
Nov 30, 2006
127
US
Having some problems when trying to loop through an aplha-numeric string where the leading zero's need to be replaced with nothing until it hits 1-9, then it would stop. This is what I have so far:

Code:
	i = 0
	lstrip_inv = InvoiceNum
	For lstrip_inv = i to len(InvoiceNum)
	lstrchar_inv = Mid(lstrip_inv, i, 1)
	Select Case lstrchar_inv
		Case <> chr(48)
			End Select
		Case chr(48) 'this is a zero, 0
			'Do Nothing
		Case Else 
			lcarry_inv = lcarry_inv & lstrchar_inv
	End Select
 
You could convert it to an integer...
Code:
Dim i as Integer
i = CInt(InvoiceNum)

If you need it to remain a string you could convert it back to a string with the CStr() function.
 
It'll spit out a Type Mismatch error out if you convert an alphanumeric string to an integer.

Regular Expressions might be a bit over the top for this but here's a regex solution anyway:
Code:
Function ReplaceLeadingZeros(strInput As String) As String

Dim re As Object
Dim result As Variant

Set re = CreateObject("VBScript.RegExp")

With re
    .Global = True
    .MultiLine = True
    .IgnoreCase = True
    .Pattern = "^0+"
    result = .Replace(strInput, "")
End With

ReplaceLeadingZeros = result

Set re = Nothing

End Function
As I say, this might be over the top but it's one way to do it [wink]

Hope this helps

HarleyQuinn
---------------------------------
Black coat, white shoes, black hat, cadillac. The boy's a timebomb!

You can hang outside in the sun all day tossing a ball around, or you can sit at your computer and do something that matters. - Eric Cartman

Get the most out of Tek-Tips, read FAQ222-2244: How to get the best answers before post
 
Regular expressions are an elegant solution but here's a brute force alternative:
Code:
a = "000123A0ABC"
For n = 1 To Len(a)
  If Left(a, 1) = "0" Then
    a = Mid(a, n)
  Else
    Exit For
  End If
Next n

Geoff Franklin
 
Ah, sorry. Missed that it was an alphanumeric. Yes, converting to integer will not work.
 

I see how you guys think, very cool... let me try this stuff out and see what happens. Yeah unfortunately its alphanum.
 
Both worked very fast, thanks again...
 
Actually had to change the if statement for the second suggestion from alvechurch, minor change: the n count was using a new string rather then the original so it was cutting off too early.

Code:
For n = 1 To Len(a)
  If Left(a, 1) = "0" Then
    a = Mid(Me.Text1, n)
  Else
    Exit For
  End If
Next n
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top