Contact US

Log In

Come Join Us!

Are you an
Engineering professional?
Join Eng-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Eng-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

VBA in Outlook

VBA in Outlook

VBA in Outlook

I've done a fair amount of VBA programming in excel but haven't tried doing so in Outlook yet.

I receive a bunch of automatically generated emails that all arrive with a single attachment. What I'd like is to take a folder in outlook that contains a group of these emails and extract the attachment and save it a system folder based on information contained in the email.

Does anybody have something that performs a similar function? I'm pretty sure I could take a skeleton routine and flesh it out. I could eventually plod my way through figuring it out, but I'm hoping for a bit of short cut.


RE: VBA in Outlook

Last time I looked the object model for Outlook is different to other Office applications, and that there are no direct methods for interacting with a file system. I did come up with a kludge that did allow for somewhat automated storage of emails via use of an associated Word method, but it wasn't pretty.

I'll see if I can't dig up some of the source code. I didn't bother saving any attachments though, those were embedded in the Microsoft specific file format.

EDMS Australia

RE: VBA in Outlook

A few code snippets from my previous Outlook Module...
Define the objects...


Dim fDialog As Office.FileDialog
Dim myOlSel As Selection
Dim proxy As Word.Application       ' Outlook doesn't support msoFileDialog objects, so steal Word's object instead. Note that msoFileDialogSaveAs is useless in this context as it doesn't support .msg
Dim myMail As Object                ' Early binding of object failed - suspect random MS Office Update 
Use the proxy object to allow the user to specify a particular path. Note that whitespace in the filepath is problematic if you want to statically define it.


' This section deals with setting up the proxy file handler. There is likely a much better way of doing this.
    Set proxy = New Word.Application      ' grab the file handler object from Word, because Outlook doesn't support. Need Word object reference included.
    proxy.Visible = False
    Set fDialog = proxy.FileDialog(msoFileDialogFolderPicker)
    fpath = "<Your_File\Path\Here>"     'Set to directory for projects.

    With fDialog
    .AllowMultiSelect = False
    .Title = "Select Project Path"
    .InitialFileName = fpath
    If .Show = -1 Then
    fpath = fDialog.SelectedItems(1)
     Exit Sub
    End If
    End With 

Some Regex trickery to remove banned characters from filepaths and some very basic error handling.


With myMail
    ' This section cleans up the subject string and removes unwanted characters
    'Two steps below assist in sorting emails by date, as well as use of hour/minute to provide uniqueness that subject header alone won't. This prevents overwriting of existing emails.
    st_TempDate = Strings.Format(.ReceivedTime, "yyyy-MM-dd")                   'Process date, use this as first part of filename
    st_TempDate = st_TempDate & "_" & Strings.Format(.ReceivedTime, "HH-mm")    'Process time, use this as second part of filename, also remove colons as this breaks the file save.
    'Next step filters subject line to remove unwanted characters from subject that may break filename conventions.
    With regEx
    .Global = True
    .MultiLine = True
    .IgnoreCase = True
    .Pattern = "[^a-zA-Z0-9 \r\t\n\f\-]"            ' Maintain normal characters, remove any characters that may cause file save issues.
    End With
    st_TempSubject = regEx.Replace(.Subject, "")
    st_FileTitle = fpath & "\" & st_TempDate & "_" & .Sender & "_" & st_TempSubject
    lngCharacters = Len(st_FileTitle)
    If lngCharacters > 255 Then             ' hard coded Windows path length restriction, if this length is exceeded then save operation will fail.
        msg_Title = "Path Length Error"
        msg_Style = vbYesNo + vbQuestion + vbDefaultButton1
        msg_Response = MsgBox("Path Length too long, path length is " & lngCharacters & ", do you want to decrease filename?", msg_Style, msg_Title, "Demo.hlp", 1000) ' User warning that mail has not been processed.
        If msg_Response = vbYes Then
           st_FileTitle = Left(st_FileTitle, 255)  ' Path length restriction is 260, need to account for file extension in string...
           Set myMail = Nothing
           Set fDialog = Nothing       'drop objects prior to exit
           Set proxy = Nothing
           Exit Sub
        End If
    End If

    'this bit finally applies the .saveas method using the resultant strings to the path specified. Method appears incapable of providing success / fail return value.

    .SaveAs st_FileTitle & ".msg", olMSG  ' Method doesn't pass success / fail return value, code thus has risk of indicating mail has been saved when operation has failed.
    .MarkAsTask (olMarkComplete)    ' Use complete flag to indicate that mail has been filed - shows as completed but doesn't set tick...
    .Close (olSave)                 ' turns out tick doesn't show up unless email is processed as closed.
    End With
    Set fDialog = Nothing       ' Release objects on macro completion.
    Set proxy = Nothing
    Set myMail = Nothing 

I've not provided the entire code for handling the data here. I don't use it anymore as we've moved on from shared drive storage for our project documents, and it was too hard to deploy the function to multiple user's PCs, but I trust you'll get the general idea.

EDMS Australia

RE: VBA in Outlook

Thanks. It may be a few days before I can try to wade my way through.

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Eng-Tips Forums free from inappropriate posts.
The Eng-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Eng-Tips forums is a member-only feature.

Click Here to join Eng-Tips and talk with other members! Already a Member? Login


Close Box

Join Eng-Tips® Today!

Join your peers on the Internet's largest technical engineering professional community.
It's easy to join and it's free.

Here's Why Members Love Eng-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close