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

Adding or Deleting Leading Zeros

Functions

Adding or Deleting Leading Zeros

by  JoanneM  Posted    (Edited  )

I noticed a few questions on other this and other forums about Leading zeroes

Sorry if this is duplicated elsewhere and I am re inventing the wheel


'Pass your value as string.

'if data is numeric use Cstr('your number or variable here')

'to convert to correct data type for the function

the Required length is the length of the string with leading zeros


Both accommodate Characters in the Values passed to them.
tested with values

?AddLeadingZeros("d4569",9)
Returns 0000d4569

? StripleadingZeros("00024c0569g00000000")
Returns 24c0569g00000000

'_____________________________________________________

[blue]

Function AddLeadingZeros(Dataval As String, RequiredLength As Integer) As String

Dim ReturnedString As String
Dim NumOfZerosToAdd As Integer

NumOfZerosToAdd = RequiredLength - Len(Dataval)
ReturnedString = String(NumOfZerosToAdd, "0") & Dataval
AddLeadingZeros = ReturnedString

End Function

[/blue]
'_____________________________________________________


[blue]
Function StripleadingZeros(Dataval As String) As String

Dim ReturnedString As String
Dim LastDigitNotZero As String
Dim PosLastdigitNotzero As Integer
Dim NumOfEndingZerosToAdd As Integer
[black]
'check for number Ending Zeros which will need to be
'replaced
[/black]
LastDigitNotZero = Left(StrReverse(Trim(Replace(Dataval, "0", Chr$(32), 1))), 1)
PosLastdigitNotzero = InStr(1, StrReverse(Dataval), LastDigitNotZero)
NumOfEndingZerosToAdd = PosLastdigitNotzero - 1
[black]
'Clear ALL Zeros & Trim away spaces
[/black]
Dataval = Trim(Replace(Dataval, "0", Chr$(32), 1))
[black]
'Replace spaces that should be zero & Replace Ending Zeros
[/black]
ReturnedString = Replace(Dataval, Chr$(32), "0", 1) & String(NumOfEndingZerosToAdd, "0")

StripleadingZeros = ReturnedString

End Function
[/blue]

'__________________________________________________


Hope this proves usefull.
Jo
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top