×
INTELLIGENT WORK FORUMS
FOR ENGINEERING PROFESSIONALS

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!
  • Students Click Here

*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

Jobs

VBA in Outlook

VBA in Outlook

VBA in Outlook

(OP)
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.

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...

CODE --> VBA

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 --> VBA

' 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 --> VBA

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

RE: VBA in Outlook

(OP)
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


Resources

White Paper - The Criticality of the E/E Architecture
Modern vehicles are highly sophisticated systems incorporating electrical, electronic, software and mechanical components. Mechanical systems are giving way to advanced software and electronic devices, driving automakers to innovate and differentiate their vehicles via the electric and electronic (E/E) architecture. As the pace of change accelerates, automotive companies need to evolve their development processes to deliver and maximize the value of these architectures. Download Now
White Paper - Model Based Engineering for Wire Harness Manufacturing
Modern cars, trucks, and other vehicles feature an ever-increasing number of sophisticated electrical and electronic features, placing a larger burden on the wiring harness that enables these new features. As complexity rises, current harness manufacturing methods are struggling to keep pace due to manual data exchanges and the inability to capture tribal knowledge. A model-based wire harness manufacturing engineering flow automates data exchange and captures tribal knowledge through design rules to help harness manufacturers improve harness quality and boost efficiency. Download Now
White Paper - Modeling and Optimizing Wire Harness Costs for Variation Complexity
This paper will focus on the quantification of the complexity related costs in harness variations in order to model them, allowing automated algorithms to optimize for these costs. A number of real world examples will be provided as well. Since no two businesses are alike, it is the aim of this paper to provide the foundational knowledge and methodology so the reader can assess their own business to model how variation complexity costs affect their business. Download Now

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