Avatar of Elena Quinn
Elena Quinn
 asked on

VBA Replace Function - What am I missing?

Hi All,

I suspect this would be fairly simple, but I am missing it.  I am simply trying to take a number that is formatted in a time format and changing them all to seconds, so I can work with the same units.  The original value is formatted with decimals, like 1.234.567.890, and it will be designated at (ns), (us), (ms), etc.  So the first thing I need to do is replace all except the first decimal.  I am trying to use the replace function for that.  But it is replacing all, despite the starting number I am entering.
Dim myArray() As Variant
Dim NumText As String
Dim DecPos As Integer
Dim i as long

i = 0
ReDim myArray(Selection.Count)

For Each cel In Selection
    myArray(i) = cel.Value
    i = i + 1
Next




For i = LBound(myArray) To UBound(myArray)
NumText = myArray(i)
DecPos = InStr(1, NumText, ".")
If DecPos > 0 Then
    If InStr(1, (Right(NumText, Len(NumText) - DecPos)), ".") > 0 Then
        NumText = Replace(NumText, ".", "", Start:=DecPos + 1)
    End If
End If

Open in new window



So NumText starts as '1.412.877.593 (s)', but after the replace function, it is '412877593 (s)'.  What happened to the "1." at the beginning?

Thanks,
Elena
VBAVisual Basic Classic

Avatar of undefined
Last Comment
Patrick Matthews

8/22/2022 - Mon
Patrick Matthews

Not sure why you would need to keep the first decimal point, but this function does it:

Function KeepOnlyFirstDecimal(InputStr As String)
    
    Dim arr As Variant
    Dim Counter As Long
    
    If InputStr <> "" Then
        arr = Split(InputStr, ".")
        If UBound(arr) > 0 Then
            KeepOnlyFirstDecimal = arr(0) & "." & arr(1)
            For Counter = 2 To UBound(arr)
                KeepOnlyFirstDecimal = KeepOnlyFirstDecimal & arr(Counter)
            Next
        Else
            KeepOnlyFirstDecimal = InputStr
        End If
    Else
        KeepOnlyFirstDecimal = InputStr
    End If
    
End Function

Open in new window

ASKER CERTIFIED SOLUTION
Norie

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Patrick Matthews

Wow, really over-thought that one :)
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23