Dayo Dayo - 1 month ago 11
Vb.net Question

Get selected mail items in Outlook Explorer with VB.Net

I am trying to convert some VBA code I have put together into an Outlook addin in order to avoid having to run the macros in reduced security environment.

I know just enough VBA and VB6 to dabble in writing stuff I use for myself and this is my first foray into VB.Net.

I just installed Visual Studio (Community Edition) and the conversion from VBA to has gone smoother than I expected thanks to suggestions by the IDE apart from one or two issues.

One of these is trying to get the items selected in Outlook which I had based on the code provided here: https://msdn.microsoft.com/en-us/library/office/ff868001.aspx

Sub GetSelectedItems()
Dim myOlExp As Outlook.Explorer
Dim myOlSel As Outlook.Selection
Dim oMail As Outlook.MailItem
Dim x As Integer

myOlExp = Application.ActiveExplorer ' => This generates an error
myOlSel = myOlExp.Selection
For x = 1 To myOlSel.Count
If myOlSel.Item(x).Class = OlObjectClass.olMail Then
Set oMail = myOlSel.Item(x)
' Do Stuff
End If
Next x
End Sub


I am unable to get around the error message generated by
Application.ActiveExplorer
.

Any advice on how to convert this to VB.Net? I have searched high and low but all the examples I have found are VBA based.

This SO Question comes close but I can't make the leap between the languages.

Answer

After hard study, I managed to resolve this using the equivalent of:

Imports Microsoft.Office.Interop.Outlook

Sub GetSelectedItems() 
    Dim myOlApp As Outlook.Application = New Outlook.Application  
    Dim myOlExp As Outlook.Explorer = myOlApp.ActiveExplorer
    Dim myOlSel As Outlook.Selection = myOlExp.Selection
    Dim oMail As Outlook.MailItem 
    Dim x As Integer 

    For x = 1 To myOlSel.Count 
        If (TypeOf myOlSel.Item(x).Class is MailItem) Then 
            oMail = myOlSel.Item(x) 
            ' Do Stuff 
        End If 
    Next x 
End Sub