Jon T
Jon T

Reputation: 145

Using regex with positive lookbehind in VBA

This is not code I wrote completely, some I have pieced together from one or two sites and some is what I have set. What I'm trying to do is use a regex function defined in regex.Pattern to look at message subject and extract a value. This is what I'm going to see in the email subject:

New Linux Server: prod-servername-a001

So far I can get the full message subject into the Excel file, but when I have tried to implement the regex portion, I get an error code 5017 (error in expression from what I can find) and the regex is not "working". My expectation is the script will pull the message subject, use the regex to extract the value and place it in the cell. I'm using RegEx Builder (regex testing program) to test the expression and it works there, but not here. I am very new to VB, so I don't know if the issue is that VB can't use this expression or if the script is failing somewhere else and the error is something residual from another problem. Or is there a better way to write this?

Sub ExportToExcel()
On Error GoTo ErrHandler

'Declarations
    Dim appExcel As Excel.Application
    Dim wkb As Excel.Workbook
    Dim wks As Excel.Worksheet
    Dim rng As Excel.Range
    Dim strSheet As String
    Dim filePath As String
    Dim strPath As String
    Dim intRowCounter As Integer
    Dim intColumnCounter As Integer
    Dim msg As Outlook.MailItem
    Dim nms As Outlook.NameSpace
    Dim fld As Outlook.MAPIFolder
    Dim itm As Object

'RegEx Declarations
    Dim result As String
    Dim allMatches As Object
    Dim regex As Object
    Set regex = CreateObject("vbscript.regexp")

    regex.Pattern = "(?<=Server: ).*"
    regex.Global = True
    regex.IgnoreCase = True


' Set the filename and path for output, requires creating the path to work
    strSheet = "outlook.xlsx"
    strPath = "D:\temp\"
    filePath = strPath & strSheet

'Debug
Debug.Print filePath

'Select export folder
    Set nms = Application.GetNamespace("MAPI")
    Set fld = nms.PickFolder

'Handle potential errors with Select Folder dialog box.
    If fld Is Nothing Then
        MsgBox "There are no mail messages to export", vbOKOnly, "Error"
        Exit Sub

    ElseIf fld.DefaultItemType <> olMailItem Then
        MsgBox "There are no mail messages to export", vbOKOnly, "Error"
        Exit Sub

    ElseIf fld.Items.Count = 0 Then
        MsgBox "There are no mail messages to export", vbOKOnly, "Error"
        Exit Sub
    End If

'Open and activate Excel workbook.
    Set appExcel = CreateObject("Excel.Application")
    appExcel.Workbooks.Open (filePath)
    Set wkb = appExcel.ActiveWorkbook
    Set wks = wkb.Sheets(1)
    wks.Activate
    appExcel.Application.Visible = True


'Copy field items in mail folder.
For Each itm In fld.Items
    intColumnCounter = 1
    Set msg = itm

    If itm.UnRead = True Then
        intRowCounter = intRowCounter + 1
        wks.Cells(1, 1).value = "Subject" 'Row 1 Column 1 (A)
        wks.Cells(1, 2).value = "Unread" 'Row 1 Column 2 (B)
        wks.Cells(1, 3).value = "Server" 'Row 1 Column 3 (C)

        Set rng = wks.Cells(intRowCounter + 1, intColumnCounter)

        If InStr(msg.Subject, "Server:") Then
        Set allMatches = regex.Execute(msg.Subject)
        rng.value = allMatches
        intColumnCounter = intColumnCounter + 1
        msg.UnRead = False                           

        Else
            rng.value = msg.Subject
            intColumnCounter = intColumnCounter + 1
            msg.UnRead = False
        End If

        Set rng = wks.Cells(intRowCounter + 1, intColumnCounter)
        rng.value = msg.UnRead
        intColumnCounter = intColumnCounter + 1
    End If

Next itm
Set appExcel = Nothing
Set wkb = Nothing
Set wks = Nothing
Set rng = Nothing
Set msg = Nothing
Set nms = Nothing
Set fld = Nothing
Set itm = Nothing
Exit Sub


ErrHandler:

If Err.Number = 1004 Then
    MsgBox filePath & " doesn't exist", vbOKOnly, "Error"

    ElseIf Err.Number = 13 Then
        MsgBox Err.Number & ": Type Mismatch", vbOKOnly, "Error"
    ElseIf Err.Number = 438 Then
        MsgBox Err.Number & ": Object doesn't support this property or method", vbOKOnly, "Error"
    ElseIf Err.Number = 5017 Then
        MsgBox Err.Number & ": Error in expression", vbOKOnly, "Error"
    Else
        MsgBox Err.Number & ": Description: ", vbOKOnly, "Error"

End If


Set appExcel = Nothing
Set wkb = Nothing
Set wks = Nothing
Set rng = Nothing
Set msg = Nothing
Set nms = Nothing
Set fld = Nothing
Set itm = Nothing

End Sub

enter image description here

Upvotes: 2

Views: 2045

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

VBA regex does not support lookbehinds, but in this case, you do not need a positive lookbehind, you just can use a capturing group - "Server: (.*)"` - and then access Group 1 value:

Set regex = CreateObject("vbscript.regexp")
regex.Pattern = "Server: (.*)"
regex.IgnoreCase = True
Set allMatches = regex.Execute("New Linux Server: prod-servername-a001")
If allMatches.Count <> 0 Then
    rng.Value = allMatches(0).Submatches(0)
End If

Here,

  • Server: - matches a string Server: + space
  • (.*) - matches and captures into Group 1 zero or more characters other than a newline up to the end of line.

See more about capturing groups.

Upvotes: 4

Related Questions