title: Check e-mails in specific time frame
body: <p>I need to check items in a folder in a specific time frame.</p>
  <p>My code goes through all the mails in the specified folder, but the folder has thousands of mails, so it takes forever.</p>
  <p>How do I check the mails only from, for example, 3/16/2015 12:00PM to 3/16/2015 2:00PM?</p>
  <p>This is what I have:</p>
  <pre class="lang-vb prettyprint-override"><code>Sub ExportToExcel()   
       
      Dim appExcel As Excel.Application
      Dim wkb As Excel.Workbook
      Dim wks As Excel.Worksheet
      Dim rng As Excel.Range
      Dim workbookFile As String
      Dim msg As Outlook.MailItem
      Dim nms As Outlook.NameSpace
      Dim fld As Outlook.MAPIFolder
      Dim itm As Object
  
       'Folder path and file name of an existing Excel workbook
       
      workbookFile = &quot;C:\Users\OutlookItems.xls&quot;
       
       'Select export folder
      Set nms = Application.GetNamespace(&quot;MAPI&quot;)
      Set fld = nms.PickFolder
       
       'Handle potential errors with Select Folder dialog box.
      If fld Is Nothing Then
          MsgBox &quot;There are no mail messages to export&quot;, vbOKOnly, _
          &quot;Error&quot;
          Exit Sub
      ElseIf fld.DefaultItemType &lt;&gt; olMailItem Then
          MsgBox &quot;There are no mail messages to export&quot;, vbOKOnly, _
          &quot;Error&quot;
          Exit Sub
      ElseIf fld.Items.Count = 0 Then
          MsgBox &quot;There are no mail messages to export&quot;, vbOKOnly, _
          &quot;Error&quot;
          Exit Sub
      End If
       
      ' Open and activate Excel workbook.
      Set appExcel = CreateObject(&quot;Excel.Application&quot;)
      Set wkb = appExcel.Workbooks.Open(workbookFile)
      Set wks = wkb.Sheets(1)
      wks.Activate
      appExcel.Application.Visible = True
      Set rng = wks.Range(&quot;A1&quot;)
       
       'Copy field items in mail folder.
       
      For Each itm In fld.Items
          If itm.Class = Outlook.OlObjectClass.olMail Then
              Set msg = itm
              If InStr(msg.Subject, &quot;Error in WU_Send&quot;) &gt; 0 And DateDiff(&quot;h&quot;, msg.SentOn, Now) &lt;= 2 Then
                  rng.Offset(0, 4).Value = msg.Body
                  Set rng = rng.Offset(1, 0)
              End If
          End If
      Next     
  End Sub
  </code></pre>
  <p>The problem lies in this part:</p>
  <pre class="lang-vb prettyprint-override"><code>    For Each itm In fld.Items
          If itm.Class = Outlook.OlObjectClass.olMail Then
              Set msg = itm
              If InStr(msg.Subject, &quot;Error in WU_Send&quot;) &gt; 0 And DateDiff(&quot;h&quot;, msg.SentOn, Now) &lt;= 2 Then
  </code></pre>
  <p>How do I look at e-mails between specified hours?</p>