How to remove FIRST leading zero in a string

K

Kermit Piper

Hello,

I have a function which removes ALL leading zeros, but is there a way
to remove only the FIRST leading zero? Any help would be greatly
appreciated. Below is my function to remove ALL leading zeros.

Thanks in advance, KP

Public Function RemoveLeadingZeros( _
ByVal strValue) As String

' Test if there is at least 1 leading zero
If Left(strValue, 1) = "0" Then

Do While True 'fContinue 'And (intPosition <= intLen)

If Mid(strValue, 1, 1) = "0" Then
strValue = Replace(strValue, "0", "", 1, 1, vbTextCompare)
Else
' reached the first non-zero string
Exit Do
End If

Loop

Else
' Does not have a leading zero
End If

RemoveLeadingZeros = strValue

End Function
 
D

Duane Hookom

I would change your existing function to allow the sending in a true or
false to decide whether only the first zero is removed.

Public Function RemoveLeadingZeros( _
ByVal strValue, Optional booFirst As Boolean = False) As String

' Test if there is at least 1 leading zero
If Left(strValue, 1) = "0" Then
If booFirst = False Then
Do While True 'fContinue 'And (intPosition <= intLen)

If Mid(strValue, 1, 1) = "0" Then
strValue = Replace(strValue, "0", "", 1, 1, vbTextCompare)
Else
' reached the first non-zero string
Exit Do
End If

Loop
Else
strValue = Mid(strValue, 2)
End If
Else
' Does not have a leading zero
End If

RemoveLeadingZeros = strValue

End Function
 
B

bwexler

Thanks Duane, but I just tested it in the immediate window with
?RemoveLeadingZeros ("00000000001234") and it returned 1234. Any other
suggestions?
 
T

Tom Lake

I have a function which removes ALL leading zeros, but is there a way
to remove only the FIRST leading zero? Any help would be greatly
appreciated. Below is my function to remove ALL leading zeros.

Thanks in advance, KP

If Left(Ltrim(strValue),1 )= "0" Then
strValue = Mid(Ltrim(strValue), 2)
End If

Tom Lake
 
J

John Spencer

If you want to remove just the first zero, then you have to call that with
the second argument as True
?RemoveLeadingZeros("00000000001234",True)

If you don't pass the optional 2nd argument, the function defaults the value
to False and strips all leading zeroes.
 
B

bwexler

OK, I was being silly. Yes, of course, I pass in as a true value and it
works. Thanks again Duane!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top