2

has VBA any good mechanism for checking, if the content of a given Excel Cell matches a specific regex?

In my case i want to know, if some cell has the format

m
m2
m1234

In fact, there's just one defined letter at the beginning, followed by a not specified amount of numbers.

How do I put this into an If-Else construct?

If Doc.Cells(1,1).Value ..... ???

greets, poeschlorn

3 Answers 3

5

You can get at the VBScript RegExp objects via Tools->References & adding "Microsoft VBScript Regular Expressions 5.5"

Alternatively a quick way to do it, if you don't need to check for a subsequent letter as in `m1234X1 is:

if Doc.Cells(1,1).Value like "[a-zA-Z]#*" then ...

(This doesn't require a reference to anything)

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

2 Comments

I didn't VB could do RegEx. That's great to know.
just another question...how do i check, if my string matches a regex like "abc_123" or "abc123" (where "abc" is always at the beginning?)
0

I don't know VBA, but the regex [a-zA-Z][0-9]* might be able to match what you want.

1 Comment

in a strange way not... [mM][0-9]* only gives m12, m1, m10
0

Here is my RegexContains function. Pass it the cell and the pattern and it will return TRUE or FALSE if it contains it or not.

Function RegexContains(ByVal find_in As String, _
                       ByVal find_what As String, _
                       Optional IgnoreCase As Boolean = False) As Boolean

Application.ScreenUpdating = False

Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.Pattern = find_what
RE.IgnoreCase = IgnoreCase
RE.Global = True
RegexContains = RE.Test(find_in)

Application.ScreenUpdating = True

End Function

Now, I'm not sure exactly what you want to find in your example, but if you want to know if the cell contains a single letter followed by one or more letters, then you would use (assuming the cell is A1): =RegexContains(A1, "^\w\d+")

  • The ^ marks the start of the sentence
  • The \w marks a single alphabetic character (a-zA-Z)
  • The \d+ marks one or more numeric characters[0-9]

I hope this helps.

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.