The basic component of Scripting Runtime is FileSystemObject, which provides methods to access files and folders. Let’s say you want to save an Outlook message attachment as a file. First, check whether a file already exists with the name you want to use. FileSystemObject provides a FileExists method to give you that information. The code
Dim fso As New Scripting.FileSystemObject
Set objAtt = objMsg.Attachments(1)
strFileName = "C:\Temp\" & objAtt.FileName
If Not fso.FileExists(strFileName) Then
objAtt.SaveAsFile strFileName
End If
saves the first attachment in a MailItem object (i.e., Outlook message) named objMsg only if the desired file name doesn’t already exist. If you later want to delete the saved file, you can use the FileSystemObject’s simple DeleteFile method:
fso.DeleteFile strFileName
FileSystemObject doesn’t have a method for opening an attached file directly from inside a message. When a user double-clicks an Outlook-item attachment to open it, Outlook saves a temporary copy of the file to the user’s system, then opens that copy. If you want to open attachments programmatically, you need to do the same thing—save a copy locally, then open the saved file.
You’ve already seen how to use the SaveAsFile method to save a message attachment as a file. To open it, you use another feature of WSH that lets you write a procedure that works similarly to double-clicking a file. When you double-click a file, Windows checks the file extension (e.g., .doc, .exe) to see what program to use to open the file. An .exe file is a program, so Windows just runs it. A .doc file is a Microsoft Word document, so Windows runs Word and opens the .doc file in Word.
WSH includes a Shell object that supports a Run method that can run any file without your specifying the program with which the file is associated. Listing 1 shows a RunFile subroutine that you can call from other procedures to open any file on your system. Note the error-handling code that deals with cases in which the file has no associated program.
Opening File Attachments
Now, we can put some of these techniques together into a useful macro that opens all the attachments in the message you’ve selected in a folder. The OpenAllFiles subroutine in Listing 2 loops through all the attachments in the item, saving each to a local folder, then calling the RunFile subroutine in Listing 1 to open the file. Note that OpenAllFiles doesn’t check first to see whether a file by the same name exists.
I’ve just scratched the surface of working with Outlook-item attachments, but you now know how to attach a file or Outlook item programmatically and how to save attached files and open those saved files. You’ve also learned about WSH and its FileSystemObject, which can help you work with files and folders in your Outlook VBA macros.