Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for pattern in a string in VBA

Tags:

vba

My requirement is that I need to check whether a string variable has first character "P" followed by digits.

For example

P0
P123
P22

To-date I have looked at options for using Like as per here.

like image 792
refactor Avatar asked Oct 24 '25 01:10

refactor


2 Answers

You can also use the native Like operator:

Sub Foo()

Dim x As String, matches As Boolean
x = "P123"

matches = (x Like "P" & Application.Rept("[0-9]", Len(x) - 1))

Debug.Print matches

End Sub
like image 136
SierraOscar Avatar answered Oct 26 '25 04:10

SierraOscar


You could use a simple RegExp:

Function strOut(strIn As String) As String
    Dim objRegex As Object
    Set objRegex = CreateObject("vbscript.regexp")
    With objRegex
        .Pattern = "^P\d+$"
        strOut = .Test(strIn)
    End With
End Function

test code

Sub Test()
Debug.Print strOut("P22")
Debug.Print strOut("aP22")
Debug.Print strOut("P12344")
End Sub
like image 35
brettdj Avatar answered Oct 26 '25 04:10

brettdj