Outlook转发和正则表达式

时间:2017-01-19 21:34:47

标签: regex vba email outlook outlook-vba

我正在尝试在Outlook中设置一条规则,每当我收到一封带有某个主题的电子邮件时,脚本就会运行并解析该电子邮件正文并返回一个长度为4-6个字符的数字。例如4444或123456.

每封进来的电子邮件只包含其中一个长度为4到6个字符的数字,以及电子邮件中的其他信息。我希望将4到6位数字返回到发送到不同地址的新电子邮件的电子邮件主题中。

这是我写的脚本。

 Sub Forward(Item As Outlook.MailItem)
    Dim M1 As MatchCollection
    Dim M As Match

    Set Reg1 = New RegExp

    With Reg1
        .Pattern = "([0-9]{4-6})"
        .Global = True
    End With
    If Reg1.Test(Item.Body) Then

        Set M1 = Reg1.Execute(Item.Body)
        For Each M In M1

'allows for multiple matches in the message body
        Item.Subject = M.SubMatches(1) & "; " & Item.Subject

        Next
    End If

 Item.Save

Set myForward = Item.Forward
myForward.Recipients.Add "xxxx@yahoo.com"

myForward.Send
End Sub

我了解如何创建规则来触发每个带有特定主题的电子邮件,但我是VBA的新手并且遇到了这个简单任务的问题。我在"测试"上得到一个对象错误而且我不确定如何解决这个问题。

1 个答案:

答案 0 :(得分:1)

你几乎得到了它,见下面的例子......

Option Explicit
Public Sub Forward(Item As Outlook.MailItem)
    Dim M1 As MatchCollection
    Dim M As Match
    Dim Reg1 As Object
    Dim myForward As Object

    Set Reg1 = New RegExp

    With Reg1
        .Pattern = "([0-9]{4,6})"
        .Global = True
    End With

    If Reg1.Test(Item.Body) Then
        Set M1 = Reg1.Execute(Item.Body)
        For Each M In M1
            Debug.Print M.SubMatches(0) ' Immediate Window

            '// allows for multiple matches in the message body
            Item.Subject = M.SubMatches(0) & "; " & Item.Subject

        Next
    End If

    Item.Save

    Set myForward = Item.Forward
    myForward.Recipients.Add "xxxx@yahoo.com"
    myForward.Display
End Sub