Microsoft Office Tutorials and References
In Depth Information
Note the use of the Instr() function. This is one of VBA’s built-in string functions. It looks for
one string in another and returns a value greater than 0 if it is found. In this example you use
Instr() to see whether the subject text you are looking for, in the variable Subject , is found
in the message’s subject, obtained as the m.Subject property.
The final step is moving the message. This is easily done with the Move method. If fDestination
is the folder you want to move the message to, and m is a reference to the message, you would write:
There’s a small wrinkle, however. If you move a message out of the Inbox before you have
completed looping through all the messages, the For Each...Next loop can sometimes be thrown
off and the process will not be completed properly. For this reason, it is necessary to keep a list of
the messages to be moved without actually moving them until the For Each...Next loop has
finished looking through the Inbox. You see how this is done in the full application presented in
Dealing with Attachments
An email message can contain one or more attachments. An attachment can be either an actual
file or a link to the file location. A MailItem object, representing an email message, has the
Attachments collection, which contains one Attachment object for each attachment
associated with the message.
When you are dealing with a received message, you can determine how many attachments the
message has from the MailItems.Attachments.Count property. If this property returns a
non-zero value, you can loop through the attachments using a For Each...Next loop:
Dim at As Outlook.Attachment
For Each at in MyMailItem.Attachments
‘ Deal with each attachment here.
The Attachment object has the following properties that you can use to work with it:
n DisplayName : The name that Outlook displays below the attachment’s icon when the
message is displayed on-screen. This is often, but not necessarily, the same as the
n FileName : The filename of the attachment.
n PathName : The full path to an attached linked file. This property is valid only for linked
n Type : The type of the attachment. Possible settings are olByValue (an attached file),
and olByReference (a link to a file).
To save an attached file (but not a linked file) to disk, call its SaveAsFile method. This method’s
one argument is the path and filename for the file. You can, but do not have to, use the original