Loop through to copy multiple outlook attachments type mismatch error

前端 未结 2 1896
一生所求
一生所求 2020-12-21 23:11

I trying to loop through the message to copy multiple attachments, but no success, i\'m getting 13 - type mismatch error!!!

Any suggestions will be appreciated.

2条回答
  •  有刺的猬
    2020-12-21 23:25

    You seem to be confusing two different kinds of loops. For Each...Next and For...Next statements have different structures. You may want to read the documentation and examples in the above linked reference.

    In a For Each loop you don't have a counter variable tracking the index. It automatically retrieves each item from the collection for you.

    In a For loop you have a counter variable that increases for you, you don't have to increment it.
    (e.g. i = i + 1)
    However if you are accessing a collection you must retrieve the current item yourself.
    (e.g. myAttachments.Item(i), or you can use the shorter equivalent syntax of myAttachments(i) as that the .Item is implied in VBA)

    Here is a working example that prints the file names for the currently active message's attachments to the Immediate window using each type of for loop.

    Public Sub TestAttachments()
        Dim message As MailItem
        Dim myAttachment As Attachment
        Dim i As Long
    
        Set message = ThisOutlookSession.ActiveInspector.CurrentItem
    
        Debug.Print "For Each...Next"
        For Each myAttachment In message.Attachments
          Debug.Print "Filename: " & myAttachment.FileName
        Next myAttachment
    
        Debug.Print "For...Next Statement"
        For i = 1 To message.Attachments.Count
          Set myAttachment = message.Attachments(i)
          Debug.Print "Index: " & i & " Filename: " & myAttachment.FileName
        Next i
    End Sub
    

    As you can see, the For Each loop is far simpler. However the For loop can give you a bit more control and information when accessing indexed collections. Usually you will want to use the For Each loop.

    Also note, there is some confusion in the terminology used for collections in VBA. There are multiple different kinds of collections. There are also Collection objects, which are a type of collection but not the only type of collection.

提交回复
热议问题