2016-05-06 105 views
0

嘗試將附件從Outlook保存到特定的文件夾,代碼將第一個附件保存在特定的mainbut,但如果它有多個附件,則會留下其他附件..嘗試使用循環但它顯示錯誤將附件從Outlook保存到特定文件夾

Public Sub SaveAttachments() 
Dim Folder As Outlook.MAPIFolder 

Dim objOL As Outlook.Application 
Dim objMsg As Outlook.MailItem 'Object 
Dim objAttachments As Outlook.Attachments 
Dim objSelection As Outlook.Selection 
Dim MailBoxName   As String 
Dim Pst_Folder_Name  As String 
Dim Pst_SubFolder_Name  As String 
Dim val 
Dim strFile As String 

'Dim oOlAp As Object, oOlns As Object, oOlInb As Object 
    ' Dim oOlItm As Object 

Dim i As Long 
Dim lngCount As Long 
Dim strFolderpath As String 

On Error GoTo ErrorHandler 

MailBoxName = ActiveSheet.Cells(1, 2).Value 
Pst_Folder_Name = ActiveSheet.Cells(2, 2).Value 
If ActiveSheet.Cells(2, 3).Value <> "" Then 
    Pst_SubFolder_Name = ActiveSheet.Cells(2, 3).Text 
    Set Folder = Outlook.Session.Folders(MailBoxName).Folders(Pst_Folder_Name).Folders(Pst_SubFolder_Name) 

Else 
    Set Folder = Outlook.Session.Folders(MailBoxName).Folders(Pst_Folder_Name) 

End If 
val = 1 


Dim myOutlook As Object: Set myOutlook = CreateObject("Outlook.application") 
Dim myNameSpace As Object: Set myNameSpace = myOutlook.GetNamespace("MAPI") 
'Dim MailFolder As Object: Set MailFolder = myNameSpace.Folders("Folder") 

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

     '~~> Check if the email actually has an attachment 
      For Each objMsg In Folder.Items 

       If objMsg.Attachments.Count <> 0 Then 
        '''''For each statement 
        i = objMsg.Attachments.Count 
        '~~> Download the attachment 
         For val = 1 To i 
         Set objAttachments = objMsg.Attachments 
         strFile = strFolderpath & objAttachments.Item(val).Filename 
         objAttachments.Item(val).SaveAsFile strFile 
      val = val + 1 

      Next 

      End If 


ErrorHandler: 
Resume Next 

End Sub 
+0

你看到什麼錯誤? – Alex

回答

0

如果你和一個集合中的項目數量不明的工作 - 使用For Each循環,而不是:

For Each objAtt In objMsg.Attachments 
    strFile = strFolderpath & objAtt.Filename 
    objAtt.SaveAsFile strFile 
Next 

但回答你的問題,具體到您現有的代碼 - 擺脫這樣的:

val = val + 1 

您已經在使用val作爲循環變量,通過遞增你每次都有效地跳過數個循環內:

For val = 1 To 10 
    Debug.Print val 
Next 

輸出:

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 

For val = 1 To 10 
    Debug.Print val 
    val = val + 1 
Next 

輸出:

1 
3 
5 
7 
9 

相關問題