2017-10-09 60 views
0

的,我有以下代码,保存所有附件发送到指定文件夹这是我最想要的时间,但我有必要只保存一个附件类型在特定情况下,说只有PDF或只有XLS。仅保存一个附件类型

什么我需要添加到我的代码来做到这一点。

我的代码:

Public Sub SavePayRoll() 
' Save data from Payroll Service 
Dim objOL As Outlook.Application 
Dim objMsg As Outlook.MailItem 'Object 
Dim objAttachments As Outlook.Attachments 
Dim objSelection As Outlook.Selection 
Dim i As Long 
Dim lngCount As Long 
Dim strFile As String 
Dim strFolderpath As String 
Dim strDeletedFiles As String 

    ' Get the path to folder 
    strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16) 
    On Error Resume Next 

    ' Instantiate an Outlook Application object. 
    Set objOL = CreateObject("Outlook.Application") 

    ' Get the collection of selected objects. 
    Set objSelection = objOL.ActiveExplorer.Selection 

' The attachment folder needs to exist 
' You can change this to another folder name of your choice 

    ' Set the Attachment folder. 
    strFolderpath = "C:\DrBox\" 



    ' Check each selected item for attachments. 
    For Each objMsg In objSelection 

    Set objAttachments = objMsg.Attachments 
    lngCount = objAttachments.Count 

    If lngCount > 0 Then 

    ' Use a count down loop for removing items 
    ' from a collection. Otherwise, the loop counter gets 
    ' confused and only every other item is removed. 

    For i = lngCount To 1 Step -1 

    ' Get the file name. 
    strFile = objAttachments.Item(i).FileName 

    ' Combine with the path to the Temp folder. 
    strFile = strFolderpath & strFile 

    ' Save the attachment as a file. 
    objAttachments.Item(i).SaveAsFile strFile 

    Next i 
    End If 

    Next 

ExitSub: 

Dim shel As String 
shel = strFolderpath 

Set objAttachments = Nothing 
Set objMsg = Nothing 
Set objSelection = Nothing 
Set objOL = Nothing 

Dim retVal As Long 
    retVal = Shell("explorer.exe " & shel, vbNormalFocus) 

End Sub 

在此先感谢

回答

0

你可以尝试检查strFile有你想要的扩展名,例如

' Get the file name. 
strFile = objAttachments.Item(i).FileName 

' Only save pdf files 
If strFile.EndsWith("pdf") Then 
    ' Combine with the path to the Temp folder. 
    strFile = strFolderpath & strFile 

    ' Save the attachment as a file. 
    objAttachments.Item(i).SaveAsFile strFile 
End If 
0

感谢@Dat你的建议给了一个错误,但你把我在正确的轨道上,我的代码现在读

dim sFileType as string 

' Get the file name. 
strFile = objAttachments.Item(i).FileName 
sFileType = LCase$(Right$(strFile, 4)) 
MsgBox (sFileType) 
' Only save pdf files 
    If sFileType = ".pdf" Then 
' Combine with the path to the Temp folder. 
strFile = strFolderpath & strFile 

' Save the attachment as a file. 
objAttachments.Item(i).SaveAsFile strFile 
    End If 

    Works fine!