Regex Function

Robert Jones

New Member
Joined
Jan 26, 2008
Messages
3
Hi People

I have searched a _lot_ for this solution, but I do not know how to do it in VBA. I want to be able to call a function in the following way:

MsgBox RegExp("abc123def456", "a(.+?)def(.+?)6", "$1Hello$2")

And for that to return: bc123Hello45

I have found many regex functions, but they very often either use fewer parameters, return $1 etc. literal in the result or appear at first to be what I am looking for but fail to work.

I would be really grateful if you could help.

Many thanks.
 

Excel Facts

What did Pito Salas invent?
Pito Salas, working for Lotus, popularized what would become to be pivot tables. It was released as Lotus Improv in 1989.
Try this

Code:
Option Explicit

Function RegexReplace(ByVal text As String, ByVal pattern As String, ByVal replacement As String) As String
    Dim regex As Object     'VBScript_RegExp_55.RegExp
    
    Set regex = CreateObject("VBScript.RegExp")   'New VBScript_RegExp_55.RegExp
    
    With regex
        .pattern = pattern
        RegexReplace = .Replace(text, replacement)
    End With
    
    Set regex = Nothing
End Function

Sub TestIt()
    MsgBox RegexReplace("abc123def456", "a(.+?)def(.+?)6", "$1Hello$2")
End Sub
 
Upvote 0

Forum statistics

Threads
1,224,521
Messages
6,179,277
Members
452,902
Latest member
Knuddeluff

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top