Vijay Penny Vijay Penny - 2 days ago 5
Vb.net Question

Outlook Error in VB.net

The below code was working perfectly in last week and now am getting this error I don't know where it went wrong.


unable to. cast com object of type 'system.__comobject' to interface type 'Microsoft.office.interop.outlook.mailitem


Try
Dim olApp As Outlook.Application
Dim olNs As Outlook.NameSpace
Dim olMail As Outlook.MailItem
Dim i As Integer

olApp = New Outlook.Application
olNs = olApp.GetNamespace("MAPI")

Dim Fldr As MAPIFolder
Fldr = olNs.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail)
i = 1

For Each olMail In Fldr.Items
If InStr(olMail.Subject, TextBox1.Text) <> 0 Then
olMail.Display()
i = i + 1
End If
Next olMail

Catch ex As System.Exception
MsgBox(Err.Description)
End Try

Answer

Probably there is/are objects other than MailItem (e.g. ReportItem, MeetingItem) in the items list. Try below

Try
    Dim olApp As Outlook.Application
    Dim olNs As Outlook.NameSpace
    Dim olMail As Outlook.MailItem
    Dim oObject As Object
    Dim i As Integer

    olApp = New Outlook.Application
    olNs = olApp.GetNamespace("MAPI")

    Dim Fldr As MAPIFolder
    Fldr = olNs.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail) 
    i = 1

    For Each oObject In Fldr.Items
        If TypeOf oObject Is Outlook.MailItem Then
            olMail = CType(oObject, Outlook.MailItem)  
            If InStr(olMail.Subject, TextBox1.Text) <> 0 Then
                olMail.Display()
                i = i + 1
            End If
        End If
    Next olMail

    Catch ex As System.Exception
        MsgBox(Err.Description)
End Try
Comments