I am trying to export Outlook emails into Excel. The code below, for some unknown reason to me, is only exporting 21 mail items. What am I doing wrong?
The array olItems has 1140 items in the count. I don't understand why the control is breaking out of the loop after 21 items.
Option Explicit
Sub list_email_info()
Dim xlApp As Excel.Application
Dim xlwb As Excel.Workbook
Dim i As Long
Dim arrHeader As Variant
Dim oINS As NameSpace
Dim oIInboxFolder As MAPIFolder
Dim olItems As Items
Dim olMailItem As MailItem
arrHeader = Array("Date Created", "Subject", "Sender's Name", "Unread")
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlwb = xlApp.Workbooks.Add
Set oINS = GetNamespace("MAPI")
Set oIInboxFolder = oINS.GetDefaultFolder(olFolderInbox).Folders("OST")
Set olItems = oIInboxFolder.Items
i = 1
On Error Resume Next
xlwb.worksheets(1).Range("A1").Resize(1, UBound(arrHeader) + 1).Value = arrHeader
For Each olMailItem In olItems
xlwb.worksheets(1).cells(i + 1, "A").Value = olItems(i).CreationTime
xlwb.worksheets(1).cells(i + 1, "B").Value = olItems(i).Subject
xlwb.worksheets(1).cells(i + 1, "C").Value = olItems(i).SenderName
xlwb.worksheets(1).cells(i + 1, "D").Value = olItems(i).UnRead
i = i + 1
Next olMailItem
MsgBox "Done"
xlwb.worksheets(1).cells.entirecolumn.autofit
Set xlwb = Nothing
Set xlApp = Nothing
Set olItems = Nothing
Set oIInboxFolder = Nothing
Set oINS = Nothing
End Sub
@Ben - I have modified as suggested, I am still getting the Type Mismatch Error
@Ben - Below error when I try to "Run" the code in the editor. This was not happening earlier.