Continue to Site

Eng-Tips is the largest engineering community on the Internet

Intelligent Work Forums for Engineering Professionals

  • Congratulations KootK on being selected by the Eng-Tips community for having the most helpful posts in the forums last week. Way to Go!

VBA in Outlook

Status
Not open for further replies.

davidbeach

Electrical
Mar 13, 2003
9,474
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.

Thanks.
 
Replies continue below

Recommended for you

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
 
A few code snippets from my previous Outlook Module...
Define the objects...
Code:
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.
Code:
' 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)
    Else
     Exit Sub
    End If
    End With

Some Regex trickery to remove banned characters from filepaths and some very basic error handling.
Code:
    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...
        Else
           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
 
Thanks. It may be a few days before I can try to wade my way through.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor