Home > database >  How to check specific email in current email box?
How to check specific email in current email box?

Time:10-04

I am working on export specific email data to excel. I am facing issue on if user typing wrong email title in userform then my code will stop with error" an object could not be found' May I know how to avoid this error if user typing wrong email title in userform and with error message."This email is not in your current outlook email box Or incorrect email title.Please choose the correct email box Or correct the email title"

Private Sub CommandButtonS_click()  'Declare outlook variables
Dim oLookInspector As Inspector
Dim oLookMailitem As MailItem 'Declare excel variables
Dim xExcelApp As Excel.Application
Dim xWb As Excel.Workbook
Dim xWs As Excel.Worksheet 'Declare word variables
Dim Wordapp As Word.Application
Dim oLookWordDoc As Word.document
Dim oLookwordTbl As Word.Table
Dim iRow As Long 'row index
Dim EmailTitle As String
EmailTitle = Me.TextBox1.Text
If Application.ActiveExplorer.CurrentFolder.Items(EmailTitle) = "" Then
    MsgBox "This email is not in your current outlook email box Or incorrect email title.Please choose the correct email box Or correct the email title"
Exit Sub
Else
Set oLookMailitem = Application.ActiveExplorer.CurrentFolder.Items(EmailTitle)    'Grab the mail item
End If

CodePudding user response:

You cannot get the item directly with Application.ActiveExplorer.CurrentFolder.Items(EmailTitle).

You could look through all the items one at a time with ActiveExplorer.CurrentFolder.Items(i).

For demonstration. This is the slowest way but sufficient for a "reasonable" number of items.
Find or Restrict is preferable.

Option Explicit

Private Sub CommandButtonS_click()  'Declare outlook variables

Dim currFolder As folder
Dim oLookObject As Object
Dim oLookMailitem As mailItem

Dim EmailTitle As String

Dim i As Long
Dim foundFlag As Boolean

EmailTitle = "Test"

Set currFolder = ActiveExplorer.CurrentFolder

' This is the slowest way but sufficient for a folder with a "reasonable" number of items.
' Find or restrict is preferable.

For i = 1 To currFolder.Items.Count

    Set oLookObject = currFolder.Items(i)
    
    If oLookObject.Class = olMail Then
    
        Set oLookMailitem = oLookObject
        
        ' Now you may check for a mailitem property
        If oLookMailitem.subject = EmailTitle Then
            Debug.Print oLookMailitem.subject
            'oLookMailitem.Display
            foundFlag = True
            Exit For    ' Stop looking when item found.
        End If
    End If
    
Next

If foundFlag = False Then
    MsgBox "This email is not in your current outlook email box Or incorrect email title." & _
      vbCr & "Please choose the correct email box Or correct the email title."
End If

End Sub
  • Related