Home >> Computing >> VBA

Regular expressions in Visual Basic.

Visual Basic for Applications

  1. In the code editor, select menu item Tools > References.
  2. Check item Microsoft VBScript Regular Expressions.
This is known to work for Office 2000.

Visual Basic 6.0

' Inspired from www.Planet-Source-Code.com

' 1.0 21-Dec-2002 Mark Carter


' Edit the vbp project file in notepad to include the following line near the
' top:
Reference=*\G{3F4DACA7-160D-11D2-A8E9-00104B365C9F}#5.5#0#..\..\..\..\WINDOWS\system32\vbscript.dll\3#Microsoft
VBScript Regular Expressions 5.5

' ... so that the .vbp will look something like:
Type=Exe
Form=Form1.frm
Reference=*\G{00020430-0000-0000-C000-000000000046}#2.0#0#..\..\..\..\WINDOWS\System32\stdole2.tlb#OLE Automation
Reference=*\G{3F4DACA7-160D-11D2-A8E9-00104B365C9F}#5.5#0#..\..\..\..\WINDOWS\system32\vbscript.dll\3#Microsoft VBScript Regular Expressions 5.5
IconForm="Form1"
' etc.

Typical Usage

You may want the following stuff in your code:
Dim re As RegExp
Set re = New RegExp
Dim s As String

re.Pattern = " m.*carter"
re.Global = False
re.IgnoreCase = True
re.MultiLine = True

s = "hello from mark carter's world"

Dim matches As MatchCollection
Set matches = re.Execute(s)

Dim mcmatch As Match
For Each mcmatch In matches
Debug.Print = mcmatch.Value
Next

Date: 15-Jul-2003