Tuesday, September 21, 2010

Outlook, REGEX and Attachments

Sub SaveAttachment(MyMail As MailItem)
    Dim strID As String
    Dim objMail As Outlook.MailItem
    Dim strFileName As String
    Dim objAttachments As Outlook.Attachments
    Dim strFilePath As String
    strFilePath = "C:\Files\"
    strID = MyMail.EntryID
    Set objMail = Application.Session.GetItemFromID(strID)
    ' Extract the date from the Subject and create the filename
    strFileName = REDate(objMail.Subject) & ".txt"
    Set objAttachments = objMail.Attachments
    ' Save the file with the name it was attached
    objAttachments.Item(1).SaveAsFile strFilePath & _
    ' Save the file with name in the format yyymmdd taken from the Subject line
    objAttachments.Item(1).SaveAsFile strFilePath & _

End Sub

Function REDate(strData As String) As String
    Dim RE As Object, REMatches As Object

    Set RE = CreateObject("vbscript.regexp")
    With RE
        .MultiLine = False
        .Global = False
        .IgnoreCase = True
        .Pattern = "[0-9]{8}"
    End With
    Set REMatches = RE.Execute(strData)
    REDate = REMatches(0)

End Function

No comments: