Home » excel » excel – VBA – Find string from beginning

excel – VBA – Find string from beginning

Posted by: admin May 14, 2020 Leave a comment

Questions:

I need to find a string “c =”, and the cell that I’m looking for, has the value of “c = 0.32”.
The problem is that in the same range, I have a cell with the value of “blablac = 54”, which comes first, and the

Dim x as Integer
x = Find("c =", MatchCase:=True).row

function, returns that one instead of the “c = 0.32” one.
How can I tell the find function to look for the string in the beginning of the cell values, so that I can obtain the right value?

How to&Answers:

You can use wildcard What:="c =*" and use LookAt:=xlWhole (for matching entire word). In that case Find will return only cells, which values starts from c =:

Dim x As Long
Dim rng As Range

Set rng = Find(What:="c =*", LookAt:=xlWhole, MatchCase:=True)

If Not rng Is Nothing Then
    x = rng.Row
End If

Answer:

Use Instr instead. That gives you the position of the first occurrence of a string.

In your case, Instr(<string>, "=") gives you the position of =. You can then use Left, Mid and Right to extract the portions the string you want.

Obviously, case is no longer relevant and you can use trim to remove any spaces around =.