Partager via


SaveAsFile Method

Saves the attachment to the specified path.

expression**.SaveAsFile(Path)**

*expression   * Required. An expression that returns an Attachment object.

Path    Required String. The location at which to save the attachment.

Example

This Visual Basic for Applications (VBA) example uses the SaveAsFile method to save the first attachment of the currently open item as a file in the C:\ folder, using the attachment's display name as the file name.

Sub SaveAttachment()
    Dim myOlApp As Outlook.Application
    Dim myInspector As Outlook.Inspector
    Dim myItem As Outlook.MailItem
    Dim myAttachments As Outlook.Attachments
    Set myOlApp = CreateObject("Outlook.Application")
    Set myInspector = myOlApp.ActiveInspector
    If Not TypeName(myInspector) = "Nothing" Then
        If TypeName(myInspector.CurrentItem) = "MailItem" Then
            Set myItem = myInspector.CurrentItem
            Set myAttachments = myItem.Attachments
            'Prompt the user for confirmation
            Dim strPrompt As String
            strPrompt = "Are you sure you want to save the first attachment in the current item to the C:\ folder? If a file with the same name already exists in the destination folder, it will be overwritten with this copy of the file."
            If MsgBox(strPrompt, vbYesNo + vbQuestion) = vbYes Then
                myAttachments.Item(1).SaveAsFile "C:\" & _
                myAttachments.Item(1).DisplayName
            End If
        Else
            MsgBox "The item is of the wrong type."
        End If
    End If
End Sub

If you use Microsoft Visual Basic Scripting Edition (VBScript) in a Microsoft Outlook form, you do not create the Application object. This example shows how to use VBScript code to save the first attachment in the current item.

Sub CommandButton1_Click()
    If TypeName(Item) = "MailItem" Then
        Set myAttachments = Item.attachments
        'Prompt the user for confirmation
        Dim strPrompt
        strPrompt = "Are you sure you want to save the first attachment to the C:\ folder? If a file with the same name already exists in the destination folder, it will be overwritten with this copy of the file."
         If MsgBox(strPrompt, vbYesNo + vbQuestion) = vbYes Then
             myAttachments.Item(1).SaveAsFile "C:\" & _
            myAttachments.Item(1).DisplayName
        End If
    Else
        MsgBox "The item is of the wrong type."
     End If
End Sub

Applies to | Attachment Object

See Also | Save Method | SaveAs Method | Saved Property | SaveSentMessageFolder Property