How to remove FIRST leading zero in a string

  • Thread starter Thread starter Kermit Piper
  • Start date Start date
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
 
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
 
Thanks Duane, but I just tested it in the immediate window with
?RemoveLeadingZeros ("00000000001234") and it returned 1234. Any other
suggestions?
 
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
 
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.
 
OK, I was being silly. Yes, of course, I pass in as a true value and it
works. Thanks again Duane!
 
Back
Top