# 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.

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

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.

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

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.

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