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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…