View Single Post
  #6   Report Post  
Posted to microsoft.public.excel.programming
GS[_6_] GS[_6_] is offline
external usenet poster
 
Posts: 1,182
Default Remove leading zeros from string


?Replace("32 01 22 88 03", "0", "")


Oops! That's going to replac *ALL* zeros; - the task is to replace *LEADING*
ZEROS ONLY!!


I devised the following solution. Maybe using regular expressions
is overkill, but it worked. Here it is:

Public Sub MyReplace()
' Include"Microsoft VBScript Regular Expressions 5.5" in Tools-References
Dim regEx As New VBScript_RegExp_55.RegExp

Dim s1 As String
Dim sFinal As String
Dim sExample As String

sExample = "01 07 08 22 88 06 04"

' Replace leading zeros (in middle of line)
regEx.Pattern = " 0"
regEx.Global = True
regEx.IgnoreCase = False
s1 = regEx.Replace(sExample, " ")

' Remove leading zeros (at beginning of line)
regEx.Pattern = "^0"
regEx.Global = True
regEx.IgnoreCase = False
sFinal = regEx.Replace(s1, "")

MsgBox sFinal

End Sub


- Robert Crandall


Yep, too much typing for me! I already have functions for various filtering
needs; here's one for removing leading zeros...


Function NoPad_Zeros$(sText$)
' Returns a string with no leading zeros
Dim vTmp, n&
Application.Volatile

vTmp = Split(sText, " ")
For n = LBound(vTmp) To UBound(vTmp)
vTmp(n) = CLng(vTmp(n))
Next 'n
NoPad_Zeros = Join(vTmp, " ")
End Function

...that you can call from code OR use as a cell formula.

In the IW:
?nopad_zeros("01 07 08 22 88 06 04")
Returns 1 7 8 22 88 6 4

In a cell:
A1 contains 01 07 08 22 88 06 04
B1 contains =nopad_zeros(A1)
displays 1 7 8 22 88 6 4

--
Garry

Free usenet access at http://www.eternal-september.org
Classic VB Users Regroup!
comp.lang.basic.visual.misc
microsoft.public.vb.general.discussion