1

I am really new to excel VBA and struggling to write a function which can extract a decimal number from an alphanumerical string like 1.25/g or 23.5g etc. The decimal number will always be in front.

I found some solutions to the problem but they don't apply to decimal numbers.

I found a solution which works for some strings but doesn't work for all. I have posted the function below. Its returning 1.2 g as 1, but works for a lot of other numbers.

Thanks in advance.

Public Function first_try(a) As Double

Dim i As Long

For i = 1 To Len(a)
If IsNumeric(Mid(a, i, 1)) Then    
    first_try = Val(Mid(a, i))
        Exit For
    End If
Next i

Debug.Print firt_try

End Function

1 Answer 1

1

Well, a shortcut could be Val function.

Public Function first_try(a) As Double
    first_try = Val(a)
End Function

As per documentation:

"The Val function stops reading the string at the first character that it can't recognize as part of a number."

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.