title: Run-time error 13 randomly while iterating emails in a public folder
body: <p>I receive a random run-time error 13 (type mismatch). This routine works most of the time. The folder passed as an argument is legitimate at the time of the failure.</p>
  <p>From what I can see in the debugger, <code>objitem</code> is missing some of the fields during runtime.  After it break-points in the debugger, I can immediately single-step (re-executing the offending line) and there is no error.</p>
  <p>I attempted using <code>on error goto</code> to sleep then retry various lines, and the error persists until it stops in the debugger.</p>
  <p>I also attempted changing between the For ii and For Each forms of the loop commands.</p>
  <p>I also temporarily disabled by anti-virus.</p>
  <p>I iterate over a large number of public folders.  My Outlook client is 2003 running under XP, and I am attached to Exchange Server version 7654.</p>
  <pre class="lang-vb prettyprint-override"><code>Sub SearchFolders(objFolder As Outlook.MAPIFolder)
      Dim objFolders As Outlook.Folders
      Dim subFolder As Outlook.MAPIFolder
      Dim objitem As MailItem
      Dim ii As Integer
  
  ' Recurse through all subfolders
      Set objFolders = objFolder.Folders
      For Each subFolder In objFolders
      Call SearchFolders(subFolder)
      Next subFolder
  
  ' Search the emails
      For ii = 1 To objFolder.Items.Count
      If objFolder.Items(ii).Class = olMail Then
          If TypeName(objFolder.Items(ii)) &lt;&gt; &quot;MailItem&quot; Then
          MsgBox (&quot;Type mismatch: object s/b MailItem and is &quot; &amp; TypeName(objFolder.Items(ii)))
          GoTo NextdblLoop
          End If
          Set objitem = objFolder.Items(ii)
          CheckEmailForErrorReports (objFolder.Items(ii))
      End If
  NextdblLoop:
      Next ii
  End Sub
  </code></pre>
  <p>Code below is modified per @dmitry suggestions and now works.</p>
  <pre class="lang-vb prettyprint-override"><code>Sub SearchFolders(objFolder As Outlook.MAPIFolder)
      Dim objFolders As Outlook.Folders
      Dim subFolder As Outlook.MAPIFolder
      Dim Objitem As Outlook.MailItem
      Dim ii As Integer
      Dim ThisItem As Object
      Dim Items As Outlook.Items
  
  ' Recurse through all subfolders
      Set objFolders = objFolder.Folders
      For Each subFolder In objFolders
      Call SearchFolders(subFolder)
      Next subFolder
  
  ' Search the emails
      Set Items = objFolder.Items
      For ii = 1 To Items.Count
      Set ThisItem = Items.item(ii)
      If ThisItem.Class = olMail Then
          If VarType(ThisItem) = 9 Then GoTo NextdblLoop
          Set Objitem = ThisItem
          CheckEmailForErrorReports (objFolder.Items(ii))
          Set Objitem = Nothing
      End If
      Set ThisItem = Nothing
  NextdblLoop:
      Next ii
      Set Items = Nothing
  End Sub
  </code></pre>