Q:

Outlook 2007+ Cast Application.ActiveExplorer.Selection.Item to Outlook.mailItem when TypeOf Item = Outlook.mailItem

take the following outlook vba:
Sub FileEmails()
    Dim myOlExp As Outlook.Explorer
    Dim myOlSel As Outlook.Selection

    Set myOlExp = Application.ActiveExplorer
    Set myOlSel = myOlExp.Selection

    If myOlSel.Count = 0 Then
        MsgBox "No objects selected."
    Else
        For Each SelectedItem In myOlSel
            If (TypeOf SelectedItem Is Outlook.mailItem) Then
                Dim mailItem As Outlook.mailItem
                Set mailItem = SelectedItem
                itemMessage = "The item is an e-mail message. The subject is " & mailItem.Subject & "."
                mailItem.Display (False)
            ElseIf (TypeOf SelectedItem Is Outlook.contactItem) Then
                Dim contactItem As Outlook.contactItem
                Set contactItem = SelectedItem
                itemMessage = "The item is a contact. The full name is " & contactItem.Subject & "."
                contactItem.Display (False)
            ElseIf (TypeOf SelectedItem Is Outlook.AppointmentItem) Then
                Dim apptItem As Outlook.AppointmentItem
                Set apptItem = SelectedItem
                itemMessage = "The item is an appointment." & apptItem.Subject & "."
            ElseIf (TypeOf SelectedItem Is Outlook.taskItem) Then
                Dim taskItem As Outlook.taskItem
                Set taskItem = SelectedItem
                itemMessage = "The item is a task. The body is " & taskItem.Body & "."
            ElseIf (TypeOf SelectedItem Is Outlook.meetingItem) Then
                Dim meetingItem As Outlook.meetingItem
                Set meetingItem = SelectedItem
                itemMessage = "The item is a meeting item. The subject is " & meetingItem.Subject & "."
            End If
        Next SelectedItem

        expMessage = expMessage & itemMessage
        MsgBox (expMessage)
    End If

End Sub

If I select a few items in my inbox and run this code, it successfully recognizes that SelectedItem is an Outlook.mailItem, but i get the following error when attempting to cast SelectedItem to Outlook.MailItem (even though the typeof argument returned true):
Object variable or with block variable not set

How can i perform this cast? I based this code on the following .net example (which makes use of TryCast):
http://msdn.microsoft.com/en-us/library/ms268994.aspx

A:

I have not tested your code but here are a couple points that might help.
Outlook VBA is not the same as VB.NET. VB.NET is a later generation and has many improvements.
One of those improvements is that you can declare variables at the block level. For VBA, variables can only be declared at the module or routine level. I do not know what happens if you re-declare variables within a loop so move all the Dim statements to the top.
VB.NET does not use SET. VBA requires SET for objects so try Set mailItem = SelectedItem.

