I'm not an expert in VBA, got an error which I can't figure out, can you please help advise?
I need an excel macro to copy from all the emails in a folder to my excel, googled and found the below code. The code runs fine for some emails, after that there will be a runtime error 440: array index out of bounds at this line.
abody = Split(objfolder.Items(i).Body, vbNewLine)
Most of the time I just record macro and edit from there so I don't really understand what is array index out of bounds.
Really hope you can enlighten me, thank you so much in advance for your help... =)
Full code can be found below...
Added in the part where the macro will get the details of the email it's processing... But what is baffling me is the received details of the email does not match the body. Can anyone please help advise?
Sub test()
Dim olApp As Object
Dim olNS As Object
Dim olFldr As Object
Dim olMail As Object
Dim i As Integer
Dim j As Long
Dim abody() As String
Dim Cnt As Long
Dim arrData() As Variant
Set olApp = CreateObject("Outlook.Application")
Set olNS = olApp.GetNamespace("MAPI")
Set olFldr = olNS.GetDefaultFolder(olFolderInbox).Folders("temp")
Cnt = 0
For Each olMail In olFldr.Items
On Error GoTo errorhandler
Cnt = Cnt + 1
abody = Split(olFldr.Items(Cnt).Body, vbNewLine)
For j = 0 To UBound(abody)
Sheet1.Cells(65000, 1).End(xlUp).Offset(1, 0).Value = abody(j)
Next
ReDim Preserve arrData(1 To 1, 1 To Cnt)
arrData(1, Cnt) = olMail.ReceivedTime
Cells(1, 1).Value = arrData(1, Cnt)
Cells(1, 1).NumberFormat = "dd/mm/yyyy hh:mm:ss AM/PM"
olFldr.Items(Cnt).Move olNS.GetDefaultFolder(6).Folders("Processed")
Next
Set olApp = Nothing
Set olNS = Nothing
Set olFldr = Nothing
errorhandler:
Application.CutCopyMode = False
Set olApp = Nothing
Set olNS = Nothing
Set olFldr = Nothing
Exit Sub
End Sub
updated code:
Sub test()
Dim olApp As Object
Dim olNS As Object
Dim olFldr As Object
Dim olMail As Object
Dim i As Integer
Dim j As Long
Dim abody() As String
Dim Cnt As Long
Dim arrData() As Variant
Dim ws As Worksheet
Set olApp = CreateObject("Outlook.Application")
Set olNS = olApp.GetNamespace("MAPI")
Set olFldr = olNS.GetDefaultFolder(olFolderInbox).Folders("temp")
Set ws = ThisWorkbook.Sheets("Sheet1")
EmailCount = olFldr.Items.Count
MsgBox "Number of emails in the folder: " & EmailCount, , "email count"
Cnt = 1
For Each olMail In olFldr.Items
abody = Split(olMail.Body, vbNewLine)
For j = 0 To UBound(abody)
ws.Cells(65000, 1).End(xlUp).Offset(1, 0).Value = abody(j)
Next
ReDim Preserve arrData(1 To 1, 1 To Cnt)
arrData(1, Cnt) = olMail.ReceivedTime
ws.Cells(1, 1).Value = arrData(1, Cnt)
ws.Cells(1, 1).NumberFormat = "dd/mm/yyyy hh:mm:ss AM/PM"
olMail.Move olNS.GetDefaultFolder(6).Folders("Processed")
Cnt = Cnt + 1
Next
Set olApp = Nothing
Set olNS = Nothing
Set olFldr = Nothing
End Sub
Can you try to change your looping part to this.
Also add the declaration and variable assignment for the target Worksheet.
Dim ws as Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1") 'added this to avoid the subscript out of range
Cnt = 1
For Each olMail In olFldr.Items
On Error GoTo errorhandler
abody = Split(olMail.Body, vbNewLine) 'changed this to olMail.Body since you are already iterating each mail
For j = 0 To UBound(abody)
ws.Cells(65000, 1).End(xlUp).Offset(1, 0).Value = abody(j) 'use the declared ws here
Next
ReDim Preserve arrData(1 To 1, 1 To Cnt)
arrData(1, Cnt) = olMail.ReceivedTime
ws.Cells(1, 1).Value = arrData(1, Cnt) 'use ws here as well if same Sheet1
ws.Cells(1, 1).NumberFormat = "dd/mm/yyyy hh:mm:ss AM/PM"
olMail.Move olNS.GetDefaultFolder(6).Folders("Processed") 'change to olMail as well
Cnt = Cnt + 1
Next
This is untested so i leave the testing to you. :)
Related
This question already has an answer here:
Need to set a date range or a 'lookback x' days in VB Macro that pulls data from Outlook to Excel
(1 answer)
Closed 9 months ago.
The community reviewed whether to reopen this question 6 months ago and left it closed:
Original close reason(s) were not resolved
Currently, I'm using VBA code to extract new hire emails from a sub inbox looking back 45 days. The emails contain data tables that I extract, so I can copy the columns. I want to avoid opening all 45 days worth of emails to copy data. Sometimes we get emails with no data table, just a sentence that reads 'no records found' which means we didn't hire or terminate anyone.
Issue: When we receive emails with no data tables, the order of dates of the emails are thrown off.
If on 6/2, 6/3, and 6/4 I get an email with data tables, and on 6/5 I get a email with no data tables, but on 6/6 (today's date) I get an email that does have data, the audit will not skip the receivedTime of 6/5 and it adds the data from 6/6 instead. When I do the audit, it displays 6/2, 6/3, 6/4, and 6/5 (with the data table from 6/6) instead of 6/2, 6/3, 6/4, and 6/6 (skipping 6/5).
Sub Extractor()
Range("A2:H30000").Clear
Dim OLApp As Outlook.Application
Set OLApp = New Outlook.Application
Dim ONS As Outlook.Namespace
Set ONS = OLApp.GetNamespace("MAPI")
Dim MYFOLDER As Outlook.Folder
Set MYFOLDER = ONS.Folders("fakeemail#fakeemail.com").Folders("Inbox")
Set MYFOLDER = MYFOLDER.Folders("NewHires")
Dim OLMAIL As Outlook.MailItem
Set OLMAIL = OLApp.CreateItem(olMailItem)
Set myItems = MYFOLDER.Items
myItems.Sort "ReceivedTime", True
For Each OLMAIL In myItems
Dim daysBack As Date
Dim dateOfEmail As Date
daysBack = VBA.Now - 45
dateOfEmail = OLMAIL.ReceivedTime
If dateOfEmail < daysBack Then Exit For
Dim oHTML As MSHTML.HTMLDocument
Set oHTML = New MSHTML.HTMLDocument
Dim oElColl As MSHTML.IHTMLElementCollection
With oHTML
.Body.innerHTML = OLMAIL.HTMLBody
Set oElColl = .getElementsByTagName("table")
End With
Dim t As Long, r As Long, c As Long
Dim eRow As Long
For t = 0 To oElColl.Length - 1
eRow = Sheets(1).Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
For r = 0 To (oElColl(t).Rows.Length - 1)
For c = 0 To (oElColl(t).Rows(r).Cells.Length - 1)
Range("A" & eRow).Offset(r, c).Value = oElColl(t).Rows(r).Cells(c).innerText
Next c
Next r
eRow = Sheets(1).Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Next t
Cells(eRow, 1) = "Sender's Name:" & " " & OLMAIL.Sender
Cells(eRow, 1).Interior.Color = vbRed
Cells(eRow, 1).Font.Color = vbWhite
Cells(eRow, 2) = OLMAIL.ReceivedTime
Cells(eRow, 2).Interior.Color = vbBlue
Cells(eRow, 2).Font.Color = vbWhite
Range(Cells(eRow, 1), Cells(eRow, 2)).Columns.AutoFit
Next OLMAIL
Range("A2").Select
Set OLApp = Nothing
Set OLMAIL = Nothing
Set oHTML = Nothing
Set oElColl = Nothing
ThisWorkbook.VBProject.VBE.MainWindow.Visible = False
End Sub
Untested, but something like this should work. Some parts split out into separate methods to keep the main logic clear.
Sub Extractor()
Const DAYS_BACK As Long = 45
Dim OLApp As Outlook.Application, ONS As Outlook.Namespace
Dim OLMAIL As Outlook.MailItem, MYFOLDER As Outlook.Folder
Dim oHTML As MSHTML.HTMLDocument, oElColl As MSHTML.IHTMLElementCollection
Dim cDest As Range, tbl As Object, myItems As Object, ws As Worksheet
Set ws = ActiveSheet 'or some specific named sheet
ws.Range("A2:H30000").Clear
Set cDest = ws.Range("A2") 'start point for copied data
Set OLApp = New Outlook.Application
Set ONS = OLApp.GetNamespace("MAPI")
Set MYFOLDER = ONS.Folders("fakeemail#fakeemail.com"). _
Folders("Inbox").Folders("NewHires")
Set myItems = MYFOLDER.Items
myItems.Sort "ReceivedTime", True
For Each OLMAIL In myItems
If OLMAIL.ReceivedTime > (VBA.Now - DAYS_BACK) Then 'within the time window?
Set oHTML = New MSHTML.HTMLDocument
With oHTML
.Body.innerHTML = OLMAIL.HTMLBody
Set oElColl = .getElementsByTagName("table")
End With
If oElColl.Length > 0 Then 'any tables to process?
AddHeader cDest, OLMAIL 'add header for this mail
For Each tbl In oElColl
TableToRange cDest, tbl 'transfer table content
Next tbl
End If
End If
Next OLMAIL
ws.Range("A1:B1").EntireColumn.AutoFit
End Sub
'copy an HTML table to a worksheet, starting at cell `cDest`
Sub TableToRange(cDest As Range, tbl As Object)
Dim r As Long, c As Long, rw As Object
For r = 0 To tbl.Rows.Length - 1
Set rw = tbl.Rows(r)
For c = 0 To rw.Cells.Length - 1
cDest.Offset(0, c).Value = rw.Cells(c).innerText
Next c
Set cDest = cDest.Offset(1, 0) 'next sheet row
Next r
End Sub
'add header info and move destination row down
Sub AddHeader(cDest As Range, oMail As Object)
With cDest
.Value = "Sender's Name:" & " " & oMail.Sender
.Interior.Color = vbRed
.Font.Color = vbWhite
.Offset(0, 1).Value = oMail.ReceivedTime
.Offset(0, 1).Interior.Color = vbBlue
.Offset(0, 1).Font.Color = vbWhite
End With
Set cDest = cDest.Offset(1, 0) 'next sheet row
End Sub
I'm trying to access calendar entries from 2 custom Outlook calendars using Excel VBA.
I've obtained some code which gives me what I want from the default calendar but I cannot see how to change the location to my own calendars.
The code I'm using is
Sub ListAppointments()
Dim olApp As Object
Dim olNS As Object
Dim olFolder As Object
Dim olApt As Object
Dim nextrow As Long
Dim FromDate As Date
Dim ToDate As Date
FromDate = CDate("30/11/2021")
ToDate = CDate("20/12/2021")
On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
If Err.Number > 0 Then Set olApp = CreateObject("Outlook.Application")
On Error GoTo 0
Set olNS = olApp.GetNamespace("MAPI")
Set olFolder = olNS.GetDefaultFolder(9)
nextrow = 2
With Sheets("Cal-Ext")
.Range("A1:E1").Value = Array("Date", "Start Time", "End Time", "Subject", "Location")
For Each olApt In olFolder.Items
If (olApt.Start >= FromDate And olApt.Start <= ToDate) Then
.Cells(nextrow, "A").Value = CDate(olApt.Start)
.Cells(nextrow, "A").NumberFormat = "DD/MM/YYYY"
.Cells(nextrow, "B").Value = olApt.Start
.Cells(nextrow, "B").NumberFormat = "HH:MM"
.Cells(nextrow, "C").Value = olApt.End
.Cells(nextrow, "C").NumberFormat = "HH:MM"
.Cells(nextrow, "D").Value = olApt.Subject
.Cells(nextrow, "E").Value = olApt.Location
nextrow = nextrow + 1
Else
End If
Next olApt
Set olFolder = olNS.GetDefaultFolder(9)
nextrow = nextrow + 5
For Each olApt In olFolder.Items
If (olApt.Start >= FromDate And olApt.Start <= ToDate) Then
.Cells(nextrow, "A").Value = CDate(olApt.Start)
.Cells(nextrow, "A").NumberFormat = "DD/MM/YYYY"
.Cells(nextrow, "B").Value = olApt.Start
.Cells(nextrow, "B").NumberFormat = "HH:MM"
.Cells(nextrow, "C").Value = olApt.End
.Cells(nextrow, "C").NumberFormat = "HH:MM"
.Cells(nextrow, "D").Value = olApt.Subject
.Cells(nextrow, "E").Value = olApt.Location
nextrow = nextrow + 1
Else
End If
Next olApt
.Columns.AutoFit
End With
Set olApt = Nothing
Set olFolder = Nothing
Set olNS = Nothing
Set olApp = Nothing
End Sub
I need to change the set olfolder command before the second loop to select my own calendar but nothing I've tried works.
Outlook calendar
Current excel result
Here is a quick code that I wrote to loop through all the navigation folders of My Calendars
This code was tested in MS Outlook. You may have to edit it for it to work in MS Excel.
Option Explicit
Sub Sample()
Dim oNameSpace As Object
Dim oExplorer As Object
Dim oMainFolder As Object
Dim oCalModule As Object
Dim oSubFolder As Object
Dim oCalNavFolders As Object
Dim i As Long
Dim objitem As Object
Set oNameSpace = Outlook.GetNamespace("MAPI")
Set oExplorer = oNameSpace.GetDefaultFolder(9).GetExplorer
Set oCalModule = oExplorer.NavigationPane.Modules.GetNavigationModule(1)
Set oCalNavFolders = oCalModule.NavigationGroups.Item("My Calendars").NavigationFolders
For i = 1 To oCalNavFolders.Count
Set objitem = oCalNavFolders(i)
On Error Resume Next
Set oSubFolder = objitem.Folder
On Error GoTo 0
If Not oSubFolder Is Nothing Then
Debug.Print oSubFolder.Name
If oSubFolder.Name = "Area1" Then
With oSubFolder
'
'~~> Do what you want
'
End With
Exit For
End If
Set oSubFolder = Nothing
End If
Next i
End Sub
Screenshot
Code from Excel
Option Explicit
Sub ListAppointments()
Dim OutApp As Object
Set OutApp = CreateObject("Outlook.Application")
Dim oNameSpace As Object
Dim oExplorer As Object
Dim oMainFolder As Object
Dim oCalModule As Object
Dim oSubFolder As Object
Dim oCalNavFolders As Object
Dim i As Long
Dim objitem As Object
Set oNameSpace = OutApp.GetNamespace("MAPI")
Set oExplorer = oNameSpace.GetDefaultFolder(9).GetExplorer
Set oCalModule = oExplorer.NavigationPane.Modules.GetNavigationModule(1)
Set oCalNavFolders = oCalModule.NavigationGroups.Item("My Calendars").NavigationFolders
For i = 1 To oCalNavFolders.Count
Set objitem = oCalNavFolders(i)
On Error Resume Next
Set oSubFolder = objitem.Folder
On Error GoTo 0
If Not oSubFolder Is Nothing Then
Debug.Print oSubFolder.Name
If oSubFolder.Name = "Area1" Then
With oSubFolder
'
'~~> Do what you want
'
End With
Exit For
End If
Set oSubFolder = Nothing
End If
Next i
End Sub
I have code that loops through all Outlook emails under a subfolder and extracts the body of the email based on the subject. Code takes a lot of time to loop through all emails as there are thousands of them.
How do I modify the code to append data, extracted from the latest emails, to the existing file instead of looping through all the emails and overwriting again & again?
Let's say I want to run the code every day to get the prior day's email data.
Option Explicit
Sub FinalMacro()
Application.DisplayAlerts = False
Dim iCounter As Integer
'iCounter = 1
Dim wkb As Workbook
Set wkb = ThisWorkbook
Sheets("Sheet1").Cells.Clear
' point to the desired email
Const strMail As String = "emailaddress#outlook.com"
Dim oApp As Outlook.Application
Dim oMapi As Outlook.MAPIFolder
'Dim oMail As Outlook.MailItem
Dim x As Long, y As Long
Dim destCell As Range
Dim i As Long
Dim oItem As Object
With ActiveSheet
Set destCell = .Cells(Rows.Count, "A").End(xlUp)
End With
On Error Resume Next
Set oApp = GetObject(, "OUTLOOK.APPLICATION")
If (oApp Is Nothing) Then Set oApp = CreateObject("OUTLOOK.APPLICATION")
On Error GoTo 0
Set oMapi = oApp.GetNamespace("MAPI").Folders(strMail).Folders("inbox").Folders("Other mails")
For Each oItem In oMapi.Items
If oItem.Subject = "Volume data" Then
' get html table from email object
Dim HTMLdoc As MSHTML.HTMLDocument
Dim tables As MSHTML.IHTMLElementCollection
Dim table As MSHTML.HTMLTable
Set HTMLdoc = New MSHTML.HTMLDocument
With HTMLdoc
.Body.innerHTML = oItem.HTMLBody
Set tables = .getElementsByTagName("table")
End With
Dim t As Long, r As Long, c As Long
Dim eRow As Long
For t = 0 To tables.Length - 1
eRow = Sheets(1).Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
For r = 0 To (tables(t).Rows.Length - 1)
For c = 0 To (tables(t).Rows(r).Cells.Length - 1)
Range("A" & eRow).Offset(r, c).Value = tables(t).Rows(r).Cells(c).innerText
Next c
Next r
eRow = Sheets(1).Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Next t
Cells(eRow, 1) = "Date & Time of Receipt:" & " " & oItem.ReceivedTime
Cells(eRow, 1).Interior.Color = vbRed
Cells(eRow, 1).Font.Color = vbWhite
Cells(eRow, 1).Columns.AutoFit
Set oApp = Nothing
Set oMapi = Nothing
Set HTMLdoc = Nothing
Set tables = Nothing
wkb.Save '"C:\Users\Desktop\Trial_1.xlsm"
End If
Next oItem
Application.DisplayAlerts = True
End Sub
To quickly select (filter) latest emails, you can use Items.Restrict.
To use your workbook for the accumulative storage of information, you just need not to erase the sheet, but to find the last filled line and add the content from the letters after it.
Smth like (not tested):
Set oMapi = oApp.GetNamespace("MAPI").Folders(strMail).Folders("inbox").Folders("Other mails")
Set wkb = ThisWorkbook
Set append_ws = wkb.Sheets("Sheet1") ' this worksheet is for appending
'Sheets("Sheet1").Cells.Clear ' - remove this statement
' set filter to: non-flagged mailitems received < 1 day ago
flt = "[FlagStatus] <> 1 And [MessageClass]='IPM.Note' And [ReceivedTime]>='" & _
Format(Now - 1, "ddddd 0:00") & "'"
Set Restricted = oMapi.Items.Restrict(flt)
For I = Restricted.Count To 1 Step -1
Set oItem = Restricted(I)
If oItem.Subject = "Volume data" Then
content_from_email = "smth from letter" ' get the content from the letter
lastrow = append_ws.Cells(append_ws.Rows.Count, 1).End(xlUp).row + 1
append_ws.Cells(lastrow, 1).Value = content_from_email
oItem.MarkAsTask olMarkComplete ' set flag to the processed items
oItem.Save
End If
Next I
I have an Excel VBA sub that is used to search for contact details in Outlook.
The function is working on many computer except one that is the primary user of this function, on which it produces the error:
Error 91: Object variable or With block variable not set
Can someone help me please?
'Function to import Outlook contacts according to their client code
Sub ExportOutlookAddressBook()
Application.ScreenUpdating = False
Dim olApp As Outlook.Application
Dim olNS As Outlook.Namespace
Dim olAL As Outlook.AddressList
Dim olEntry As Outlook.AddressEntry
Dim CodeClient As String
Dim RCompanyName As String
Dim i As Integer
Dim AccountCount As Integer
Set olApp = Outlook.Application
Set olNS = olApp.GetNamespace("MAPI")
CodeClient = 0
RCompanyName = 0
i = 0
AccountCount = olNS.Accounts.Count
Range("AA6:AF10").ClearContents
For i = 1 To AccountCount
Set olAL = olNS.AddressLists(i) 'Change name if different contacts list name
Set olEntry = olAL.AddressEntries(1)
ActiveWorkbook.ActiveSheet.Range("K6").Select
CodeClient = ActiveCell.Value
ActiveWorkbook.ActiveSheet.Range("AA6").Select
For Each olEntry In olAL.AddressEntries
' your looping code here
RCompanyName = Left(Right(olEntry.GetContact.CompanyName, 7), 6)
If RCompanyName = CodeClient Then
ActiveCell.Value = olEntry.GetContact.FullName
ActiveCell.Offset(0, 1).Value = olEntry.GetContact.BusinessTelephoneNumber 'business phone number
ActiveCell.Offset(0, 2).Value = olEntry.Address 'email address
ActiveCell.Offset(0, 3).Value = olEntry.GetContact.CompanyName
ActiveCell.Offset(0, 4).Value = olEntry.GetContact.BusinessAddress
ActiveCell.Offset(1, 0).Select
End If
Next olEntry
Next i
Set olApp = Nothing
Set olNS = Nothing
Set olAL = Nothing
Application.ScreenUpdating = True
ActiveWorkbook.ActiveSheet.Range("K7").Select
End Sub
Try this.
Besides adding the If Nothing...'s, I tidied some of the other repetative code.
Option Explicit 'this line is recommended at the very top of every module.
'Function to import Outlook contacts according to their client code
Sub ExportOutlookAddressBook()
Dim olApp As Outlook.Application, olNS As Outlook.Namespace, olAL As Outlook.AddressList
Dim olEntry As Outlook.AddressEntry, CodeClient As String, RCompanyName As String, i As Long
Set olApp = Outlook.Application
Set olNS = olApp.GetNamespace("MAPI")
Application.ScreenUpdating = False
Range("AA6:AF10").ClearContents
For i = 1 To olNS.Accounts.Count
Set olAL = olNS.AddressLists(i) 'Change name if different contacts list name
Set olEntry = olAL.AddressEntries(1)
CodeClient = ActiveWorkbook.ActiveSheet.Range("K6")
ActiveWorkbook.ActiveSheet.Range("AA6").Select
For Each olEntry In olAL.AddressEntries
' your looping code here
RCompanyName = Left(Right(olEntry.GetContact.CompanyName, 7), 6)
If RCompanyName = CodeClient Then
With ActiveCell
.Value = olEntry.GetContact.FullName
.Offset(0, 1) = olEntry.GetContact.BusinessTelephoneNumber 'business phone number
.Offset(0, 2) = olEntry.Address 'email address
If Not olEntry.GetContact Is Nothing Then
If Not olEntry.GetContact.CompanyName Is Nothing Then
.Offset(0, 3) = olEntry.GetContact.CompanyName
End If
If Not olEntry.GetContact.BusinessAddress Is Nothing Then
.Offset(0, 4) = olEntry.GetContact.BusinessAddress
End If
End If
.Offset(1, 0).Select
End With
End If
Next olEntry
Next i
Set olApp = Nothing
Set olNS = Nothing
Set olAL = Nothing
Application.ScreenUpdating = True
ActiveWorkbook.ActiveSheet.Range("K7").Select
End Sub
I am to write a VBA code that would retrive emails from Outlook based on certain conditions. The problem I have is that I have to denote a certain folder in my code (in the example below the folder denoted is "PRE Costumer". I would like to retrive all emails from my 'inbox' or in better case from all outlook folders. The problem is that my inbox consists of many subfolders (because of rules0. My problem is that I may not know all the subfolders names (as many useres are going to use the macro and even someone can have the e mails in Personal Folders).
Could you please advise is there a way to overcome this problem?
Please let me know if this question is vague (as I am newcomer)
Please find the line that I have probelm with marked with a comment.
Sub GetFromInbox()
Dim olApp As Outlook.Application
Dim olNs As Namespace
Dim Fldr As MAPIFolder
Dim olMail As Variant
Dim i As Integer
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
'Below is the line I have problem with
Set Fldr = olNs.GetDefaultFolder(olFolderInbox).Folders("PRE Customer")
i = 1
x = Date
For Each olMail In Fldr.Items
If InStr(olMail.Subject, "transactions") > 0 _
And InStr(olMail.ReceivedTime, x) > 0 Then
ActiveSheet.Cells(i, 1).Value = olMail.Subject
ActiveSheet.Cells(i, 2).Value = olMail.ReceivedTime
ActiveSheet.Cells(i, 3).Value = olMail.SenderName
i = i + 1
End If
Next olMail
Set Fldr = Nothing
Set olNs = Nothing
Set olApp = Nothing
End Sub
Just loop through all the folders in Inbox.
Something like this would work.
Edit1: This will avoid blank rows.
Sub test()
Dim olApp As Outlook.Application, olNs As Outlook.Namespace
Dim olFolder As Outlook.MAPIFolder, olMail As Outlook.MailItem
Dim eFolder As Outlook.Folder '~~> additional declaration
Dim i As Long
Dim x As Date, ws As Worksheet '~~> declare WS variable instead
Dim lrow As Long '~~> additional declaration
Set ws = Activesheet '~~> or you can be more explicit using the next line
'Set ws = Thisworkbook.Sheets("YourTargetSheet")
Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
x = Date
For Each eFolder In olNs.GetDefaultFolder(olFolderInbox).Folders
'Debug.Print eFolder.Name
Set olFolder = olNs.GetDefaultFolder(olFolderInbox).Folders(eFolder.Name)
For i = olFolder.Items.Count To 1 Step -1
If TypeOf olFolder.Items(i) Is MailItem Then
Set olMail = olFolder.Items(i)
If InStr(olMail.Subject, "transactions") > 0 _
And InStr(olMail.ReceivedTime, x) > 0 Then
With ws
lrow = .Range("A" & .Rows.Count).End(xlup).Row
.Range("A" & lrow).Offset(1,0).value = olMail.Subject
.Range("A" & lrow).Offset(1,1).Value = olMail.ReceivedTime
.Range("A" & lrow).Offset(1,2).Value = olMail.SenderName
End With
End If
End If
Next i
Set olFolder = Nothing
Next eFolder
End Sub
Above takes care of all subfolders in Inbox.
Is this what you're trying?
To fix your error (olFolderInbox is a Outlook only constant, so you need to define it in vba that is not Outlook):
Const olFolderInbox = 6
'...
Set Fldr = olNs.GetDefaultFolder(olFolderInbox).Folders("PRE Customer")
Also to prevent missing Reference when run from another computer, I would:
Dim olApp As Object
Dim olNs As Object
Dim Fldr As Object
Dim olMail As Object
Dim i As Long
Set olApp = CreateObject("Outlook.Application")
'...
You might also want to disable ScreenUpdating, then enable it in Excel if you expect a long list.
UPDATE (Solution for all folders from a Root Folder)
I used something slightly different for comparing the dates.
Option Explicit
Private lRow As Long, x As Date, oWS As Worksheet
Sub GetFromInbox()
Const olFolderInbox = 6
Dim olApp As Object, olNs As Object
Dim oRootFldr As Object ' Root folder to start
Dim lCalcMode As Long
Set olApp = CreateObject("Outlook.Application")
Set olNs = olApp.GetNamespace("MAPI")
Set oRootFldr = olNs.GetDefaultFolder(olFolderInbox).Folders("PRE Customer")
Set oWS = ActiveSheet
x = Date
lRow = 1
lCalcMode = Application.Calculation
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
GetFromFolder oRootFldr
Application.ScreenUpdating = True
Application.Calculation = lCalcMode
Set oWS = Nothing
Set oRootFldr = Nothing
Set olNs = Nothing
Set olApp = Nothing
End Sub
Private Sub GetFromFolder(oFldr As Object)
Dim oItem As Object, oSubFldr As Object
' Process all mail items in this folder
For Each oItem In oFldr.Items
If TypeName(oItem) = "MailItem" Then
With oItem
If InStr(1, .Subject, "transactions", vbTextCompare) > 0 And DateDiff("d", .ReceivedTime, x) = 0 Then
oWS.Cells(lRow, 1).Value = .Subject
oWS.Cells(lRow, 2).Value = .ReceivedTime
oWS.Cells(lRow, 3).Value = .SenderName
lRow = lRow + 1
End If
End With
End If
Next
' Recurse all Subfolders
For Each oSubFldr In oFldr.Folders
GetFromFolder oSubFldr
Next
End Sub