I'm trying to write a macro to automatically save certain reports we get via email at work. Another department has something very similar in place, so I can re-use a lot of their code. However, they couldn’t really explain to me what certain parts of the code do and googling it wasn't particularly helpful.
If it helps, I’ll post the whole code, I left it out because a) I’d have to edit some things (names etc) and b) I don’t think it’s relevant to my problem.
The point of the code is that on startup the macro starts; every new email gets then checked (by sender; subject line; attachments). I struggle understanding the startup-part of the code because I’m not that experienced with VBA in general and have never used VBA in Outlook.
Option Explicit
Private WithEvents olInboxItems As Items
Private Sub Application_Startup()
Dim objNS As NameSpace
Set objNS = Application.Session
Set olInboxItems = objNS.GetDefaultFolder(olFolderInbox).Folders("reports").Items
Set objNS = Nothing
End Sub
Private Sub olInboxItems_ItemAdd(ByVal Item As Object)
If Item.Attachments.Count > 0 Then
….
End Sub
Questions:
Private WithEvents olInboxItems As Items
- What does Private WithEvents
mean or do? I know about events in VBA, like opening a workbook, but I couldn’t figure out what was meant with this line.
NameSpace
: Simply put, what is a NameSpace? What I read was that in Outlook there’s a different structure to the object model compared to say Excel, the NameSpace is just below the application level. If that’s correct, then I guess that’s good enough for me, but if anyone has a neat explanation, I’d appreciate it.
Why would you Set objNS = Nothing
?
Private WithEvents olInboxItems As Items - What does Private WithEvents mean or do?
WithEvents Specifies one or more declared member variables refer to an instance of a class that can raise events.
To create an event handler for Microsoft Outlook objects in Microsoft Visual Basic see
Using Events with Automation MSDN
Using Outlook Visual Basic for Applications to Respond to Outlook Events MSDN
NameSpace: Simply put, what is a NameSpace?
NameSpace object (Outlook) it represents an abstract root object for any data source and accessing storage objects directly.
NameSpace object (Outlook) MSDN
good code example
Option Explicit
Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Dim olNs As Outlook.NameSpace
Set olNs = Application.GetNamespace("MAPI")
Dim Inbox As Outlook.MAPIFolder
Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
Set Items = Inbox.Items
End Sub
Private Sub Items_ItemAdd(ByVal Item As Object)
If TypeOf Item Is Outlook.MailItem Then
DoEvents
'' call another sub
End If
End Sub
Setting Object to Nothing - https://stackoverflow.com/a/517202/4539709