I need to download the all the emails in a particular to excel. I found a code which works pretty close, but the mail content are not pasting in a single cell.
And I would also like to have only particular details of the body. Can some one help me in modifying the below code for..
*updated:
I would need only part of mail content (as marked below) to be downloaded to excel.
Could you please help me with this.
Excel VBA Code:
Sub GetMail()
Dim olApp As Object
Dim olFolder As Object
Dim olMailItem As Object
Dim strTo As String
Dim strFrom As String
Dim dateSent As Variant
Dim dateReceived As Variant
Dim strSubject As String
Dim spBody As Variant
Dim loopControl As Variant
Dim mailCount As Long
Dim totalItems As Long
'-------------------------------------------------------------
'//Turn off screen updating
Application.ScreenUpdating = False
'//Setup headers for information
Range("A1:F1").Value = Array("To", "From", "Subject", "Body", "Sent (from Sender)", "Received (by Recipient)")
'//Format columns E and F to
Columns("E:F").EntireColumn.NumberFormat = "DD/MM/YYYY HH:MM:SS"
'//Create instance of Outlook
Set olApp = CreateObject("Outlook.Application")
'//Select folder to extract mail from
Set olFolder = olApp.GetNamespace("MAPI").PickFolder
'//Get count of mail items
totalItems = olFolder.Items.Count
mailCount = 0
'//Loop through mail items in folder
For Each loopControl In olFolder.Items
'//If loopControl is a mail item then continue
If TypeName(loopControl) = "MailItem" Then
'//Increase mailCount
mailCount = mailCount + 1
'//Inform user of item count in status bar
Application.StatusBar = "Reading email no. " & mailCount & " of " & totalItems
'//Get mail item
Set olMailItem = loopControl
'//Get Details
With olMailItem
strTo = .To
'//If strTo begins with "=" then place an apostrophe in front to denote text format
If Left(strTo, 1) = "=" Then strTo = "'" & strTo
strFrom = .Sender
'//If sender displays name only, show name followed by email address e.g.(Bloggs, Joe < j.bloggs#mail.com >)
If InStr(1, strFrom, "#") < 1 Then strFrom = strFrom & " - < " & .SenderEmailAddress & " >"
dateSent = .SentOn
dateReceived = .ReceivedTime
strSubject = .Subject
spBody = Split(.Body, vbCrLf)
End With
'//Place information into spreadsheet
'//import information starting from last blank row in column A
With Range("C" & Rows.Count).End(xlUp).Offset(1, -2)
.Value = strTo
.Offset(0, 1).Value = strFrom
.Offset(0, 2).Value = strSubject
.Offset(0, 3).Resize(UBound(spBody) + 1, 1).Value = WorksheetFunction.Transpose(spBody)
.Offset(0, 4).Value = dateSent
.Offset(0, 5).Value = dateReceived
End With
'//Release item from memory
Set olMailItem = Nothing
End If
'//Next Item
Next loopControl
'//Release items from memory
Set olFolder = Nothing
Set olApp = Nothing
'//Resume screen updating
Application.ScreenUpdating = False
'//reset status bar
Application.StatusBar = False
'//Inform user that code has finished
MsgBox mailCount & " messages copied successfully.", vbInformation, "Complete"
End Sub
"but the mail content are not pasting in a single cell"
change:
Dim spBody As Variant
to:
Dim spBody As String
then change:
spBody = Split(.body, vbCrLf) '<--| Split() function is "splitting" the mail body into an array with as many elements as vbCrlf occurrences plus one
to:
spBody = .body
and finally change:
.Offset(0, 3).Resize(UBound(spBody) + 1, 1).Value = WorksheetFunction.Transpose(spBody) '<--| Resize() is "widening" the range to write values in to as many rows as 'spBody' array elements
to:
.Offset(0, 3).Value = spBody
Related
Sub SendEmail()
Dim OutlookApp As Object
Dim MItem As Object
Dim cell As Range
Dim email_ As String
Dim cc_ As String
Dim subject_ As String
Dim body_ As String
Dim attach_ As String
Dim StrBody As String
'Create Outlook object
Set OutlookApp = CreateObject("Outlook.Application")
'Loop through the rows
For Each cell In Sheets("publico").Range("H2:H2000").Cells.SpecialCells(xlCellTypeConstants)
If cell.Row <> 1 Then
If cell.Value <> "" Then ' to check email address cell is empty or not
email_ = cell.Value ' email address mention in the F column
Else
email_ = cell.Offset(0, 1).Value 'alternative email address
End If
subject_ = Sheets("CAPA").Range("D1").Value 'as of now i mentioned column B as subject, change the value accordingly
' body_ = Sheets("CAPA").Range("D2").Value 'please change the offset value based on the body content cell
StrBody = Sheets("CAPA").Range("D2").Value & "<br><br>" & _
Sheets("CAPA").Range("D3").Value & "<br><br>" & _
Sheets("CAPA").Range("F7").Value & "<br><br><br>"
**Sheets("publico").Range**
' cc_ = cell.Offset(0, 3).Value ' remove comments if you are going to use the cc and also change the offset value according to cc mail address cell value.
' attach_ = cell.Offset(0, 4).Value ' remove comments "'" if you going attache any file and change the offset value based on the attachment value position.
'Create Mail Item and send it
Set MItem = OutlookApp.CreateItem(0)
With MItem
.To = email_
' .CC = cc_
.Subject = subject_
.HTMLBody = StrBody
'.Attachments.Add attach_
'.Display
End With
MItem.Send
Sheets("publico").Range("J2").Value = "enviado"
End If
Next
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
So, for branch 100, manager 15, I will send line 1 and 2 of the sheet, to the manager mail only.
In the case of no manager assigned, the email will be directed to the head (email2).
After sending an e-mail, the F column must generate a log "OK".
EDIT:
I edited the code provided and the e-mail is going to the proper recipients.
Please try the below code.
Sub SendEmail()
Dim OutlookApp As Object
Dim MItem As Object
Dim cell As Range
Dim email_ As String
Dim cc_ As String
Dim subject_ As String
Dim body_ As String
Dim attach_ As String
'Create Outlook object
Set OutlookApp = CreateObject("Outlook.Application")
'Loop through the rows
For Each cell In Columns("f").Cells.SpecialCells(xlCellTypeConstants)
If cell.Row <> 1 Then
If cell.Value <> "" Then ' to check email address cell is empty or not
email_ = cell.Value 'email address mention in the F column
Else
email_ = cell.Offset(0, 1).Value 'alternative email address
End If
subject_ = cell.Offset(0, -4).Value 'as of now i mentioned column B as subject, change the value accordingly
body_ = cell.Offset(0, 2).Value 'please change the offset value based on the body content cell
' cc_ = cell.Offset(0, 3).Value ' remove comments if you are going to use the cc and also change the offset value according to cc mail address cell value.
' attach_ = cell.Offset(0, 4).Value ' remove comments "'" if you going attache any file and change the offset value based on the attachment value position.
'Create Mail Item and send it
Set MItem = OutlookApp.CreateItem(0)
With MItem
.To = email_
' .CC = cc_
.Subject = subject_
.Body = body_
'.Attachments.Add attach_
'.Display
End With
MItem.Send
cell.Value = "ok"
End If
Next
End Sub
Thanks,
Arun
If someone could help me from going insane, my mother would appreciate it.
I have a long list of email addresses (many repeats) with associated Audit Locations. Basically I need to create one email for each email address and populate said email body with a list of all the associated Audit Locations.
e.g.
Column One (Email Address) | Column 2 (Audit Location)
Yoda1#lightside.org | Coruscant
Yoda1#lightside.org | Death Star
Yoda1#lightside.org | Tatooine
Vader#Darkside.org | Death Star
Vader#Darkside.org | Coruscant
Jarjar#terrible.org | Yavin
So far I have created a CommandButton Controlled vba that takes Column One and makes it unique in a new worksheet.
Then I have another sub that creates an email for each unique email address. But I am stuck on the "If...Then" statement. Essentially, I want to add the information in Column 2 (Audit Location) if the Recipient of the email is the email address in Column One and then continue to append to the email body until the email address no longer equals the recipient email address. Any guidance would be huge.
Private Sub CommandButton1_Click()
Call MakeUnique
Call EmailOut
End Sub
Sub MakeUnique()
Dim vaData As Variant
Dim colUnique As Collection
Dim aOutput() As Variant
Dim i As Long
'Put the data in an array
vaData = Sheet1.Range("A:A").Value
'Create a new collection
Set colUnique = New Collection
'Loop through the data
For i = LBound(vaData, 1) To UBound(vaData, 1)
'Collections can't have duplicate keys, so try to
'add each item to the collection ignoring errors.
'Only unique items will be added
On Error Resume Next
colUnique.Add vaData(i, 1), CStr(vaData(i, 1))
On Error GoTo 0
Next i
'size an array to write out to the sheet
ReDim aOutput(1 To colUnique.Count, 1 To 1)
'Loop through the collection and fill the output array
For i = 1 To colUnique.Count
aOutput(i, 1) = colUnique.Item(i)
Next i
'Write the unique values to column B
Sheets.Add.Name = "Unique"
ActiveSheet.Range("A1").Resize(UBound(aOutput, 1), UBound(aOutput, 2)).Value = aOutput
End Sub
Sub EmailOut()
Dim xOutApp As Object
Dim xOutMail As Object
Dim xMailBody As String
On Error Resume Next
Dim cell As Range
For Each cell In Worksheets("Unique").Columns("a").Cells.SpecialCells(xlCellTypeConstants)
recip = cell.Value
Set xOutApp = CreateObject("Outlook.Application")
Set xOutMail = xOutApp.CreateItem(0)
For Each org In Columns("b").Cells.SpecialCells(xlCellTypeConstants)
If org.Value Like recip Then
xMailBody = "Body content" & vbNewLine & vbNewLine & _
"This is line 1" & " " & cell.Offset(0, 3).Value & vbNewLine & _
[B5] & vbNewLine & _
"This is line 2"
End If
Next org
On Error Resume Next
With xOutMail
.To = recip
.CC = ""
.BCC = ""
.Subject = cell.Offset(0, 2).Value & " " & cell.Offset(0, 3).Value & " " & "Remittance Advice"
.Body = xMailBody
.Display 'or use .Send
End With
On Error GoTo 0
Set xOutMail = Nothing
Set xOutApp = Nothing
Next
End Sub
Based on your example I quickly wrote the following:
Option Explicit
Public Sub SendEmails()
Dim dictEmailData As Object
Dim CurrentWorkBook As Workbook
Dim WrkSht As Worksheet
Dim rngToLookUp As Range
Dim lngLastRow As Long, i As Long
Dim arryEmailData As Variant
Dim objOutlookApp As Object, objOutlookEmail As Object
Dim varKey As Variant
Application.ScreenUpdating = False
Set CurrentWorkBook = Workbooks("SomeWBName")
Set WrkSht = CurrentWorkBook.Worksheets("SomeWSName")
lngLastRow = WrkSht.Cells(WrkSht.Rows.Count, "A").End(xlUp).Row 'Find last row with data
Set rngToLookUp = WrkSht.Range("A2:B" & lngLastRow) 'set range for last row of data
arryEmailData = rngToLookUp.Value2 'Get the email data from the sheet into an array
Set dictEmailData = CreateObject("Scripting.Dictionary") 'set the dicitonary object
On Error GoTo CleanFail
For i = LBound(arryEmailData, 1) To UBound(arryEmailData, 1)
varKey = UCase(Trim(arryEmailData(i, 1)))
If Not dictEmailData.Exists(varKey) Then
dictEmailData(varKey) = vbNewLine & vbNewLine & Trim(arryEmailData(i, 2))
Else
dictEmailData(varKey) = dictEmailData(varKey) & vbNewLine & Trim(arryEmailData(i, 2))
End If
varKey = Empty
Next i
'for each unique key in the dicitonary
'get the corresponding item
'created in the loop above
Set objOutlookApp = CreateObject("Outlook.Application") 'set the outlook object
Dim Msg As String, MailBody As String
For Each varKey In dictEmailData.Keys
Msg = dictEmailData.Item(varKey)
Set objOutlookEmail = objOutlookApp.CreateItem(0)
MailBody = "Dear Colleague," & Msg
With objOutlookEmail
.To = varKey
.Subject = "Remittance Advice"
.Body = MailBody
.Send
End With
Set objOutlookEmail = Nothing
Msg = Empty: MailBody = Empty
Next
MsgBox "All Emails have been sent", vbInformation
CleanExit:
Set objOutlookApp = Nothing
Application.ScreenUpdating = True
Exit Sub
CleanFail:
Resume CleanExit
End Sub
Add the first occurrence of a varKey = email address to the dictionary dictEmailData along with its corresponding item dictEmailData(varKey) = Email body. On the next occurrence of the email address, append to the Email body. Once the dictionary is built, loop through it and send the emails
Printing to the immediate window yields:
New to VBA, attempting to list my outlook emails in excel given a specific time period. Found code to list my emails, but can't figure out how to restrict it to a time period, any ideas?
Sub GetMail()
Dim OLApp As Object
Dim olFolder As Object
Dim olMailItem As Object
Dim strTo As String
Dim strFrom As String
Dim dateSent As Variant
Dim dateReceived As Variant
Dim strSubject As String
Dim strBody As String
Dim loopControl As Variant
Dim mailCount As Long
Dim totalItems As Long
'-------------------------------------------------------------
Application.ScreenUpdating = False
Range("A1:F1").Value = Array("To", "From", "Subject", "Body", "Sent (from Sender)", "Received (by Recipient)")
Columns("E:F").EntireColumn.NumberFormat = "DD/MM/YYYY HH:MM:SS"
Set OLApp = CreateObject("Outlook.Application")
Set olFolder = OLApp.GetNamespace("MAPI").PickFolder
totalItems = olFolder.items.Count
mailCount = 0
For Each loopControl In olFolder.items
'//If loopControl is a mail item then continue
If TypeName(loopControl) = "MailItem" Then
mailCount = mailCount + 1
Application.StatusBar = "Reading email no. " & mailCount & " of " & totalItems
Set olMailItem = loopControl
With olMailItem
strTo = .To
If Left(strTo, 1) = "=" Then strTo = "'" & strTo
strFrom = .Sender
If InStr(1, strFrom, "#") < 1 Then strFrom = strFrom & " - < " & .SenderEmailAddress & " >"
dateSent = .Body
dateReceived = .ReceivedTime
strSubject = .Subject
End With
With Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
.Value = strTo
.Offset(0, 1).Value = strFrom
.Offset(0, 2).Value = strSubject
If InStr(0, strBody, "From:") > 0 Then
'//If exists, copy start of email body, up to the position of "From:"
.Offset(0, 3).Value = Mid(strBody, 1, InStr(1, strBody, "From:") - 1)
Else
.Offset(0, 3).Value = strBody
End If
.Offset(0, 4).Value = dateSent
.Offset(0, 5).Value = dateReceived
End With
Set olMailItem = Nothing
End If
Next loopControl
Set olFolder = Nothing
Set OLApp = Nothing
Application.ScreenUpdating = True
Application.StatusBar = False
MsgBox mailCount & " messages copied successfully.", vbInformation, "Complete"
End Sub
New to VBA, attempting to list my outlook emails in excel given a specific time period. Found code to list my emails, but can't figure out how to restrict it to a time period, any ideas?
Try This. Added 2 date variables date1 and date2. Adjust these as per your requirements.
Option Explicit
Sub GetMail()
Dim OLApp As Object
Dim olFolder As Object
Dim olMailItem As Object
Dim date1 As Date
Dim date2 As Date
Dim strTo As String
Dim strFrom As String
Dim dateSent As Variant
Dim dateReceived As Variant
Dim strSubject As String
Dim strBody As String
Dim loopControl As Variant
Dim mailCount As Long
Dim totalItems As Long
'-------------------------------------------------------------
date2 = Now()
date1 = Now() - 3
Application.ScreenUpdating = False
Range("A1:F1").Value = Array("To", "From", "Subject", "Body", "Sent (from Sender)", "Received (by Recipient)")
Columns("E:F").EntireColumn.NumberFormat = "DD/MM/YYYY HH:MM:SS"
Set OLApp = CreateObject("Outlook.Application")
Set olFolder = OLApp.GetNamespace("MAPI").PickFolder
totalItems = olFolder.Items.Count
mailCount = 0
For Each loopControl In olFolder.Items
'//If loopControl is a mail item then continue
If TypeName(loopControl) = "MailItem" Then
mailCount = mailCount + 1
Application.StatusBar = "Reading email no. " & mailCount & " of " & totalItems
Set olMailItem = loopControl
With olMailItem
strTo = .To
If Left(strTo, 1) = "=" Then strTo = "'" & strTo
strFrom = .Sender
If InStr(1, strFrom, "#") < 1 Then strFrom = strFrom & " - < " & .SenderEmailAddress & " >"
dateSent = .body
dateReceived = .ReceivedTime
strSubject = .Subject
End With
If dateReceived <= date2 And dateReceived >= date1 Then
With Range("A" & Rows.Count).End(xlUp).Offset(1, 0)
.Value = strTo
.Offset(0, 1).Value = strFrom
.Offset(0, 2).Value = strSubject
If InStr(0, strBody, "From:") > 0 Then
'//If exists, copy start of email body, up to the position of "From:"
.Offset(0, 3).Value = Mid(strBody, 1, InStr(1, strBody, "From:") - 1)
Else
.Offset(0, 3).Value = strBody
End If
.Offset(0, 4).Value = dateSent
.Offset(0, 5).Value = dateReceived
End With
End If
Set olMailItem = Nothing
End If
Next loopControl
Set olFolder = Nothing
Set OLApp = Nothing
Application.ScreenUpdating = True
Application.StatusBar = False
MsgBox mailCount & " messages copied successfully.", vbInformation, "Complete"
End Sub
There are 3 body contents to be picked based on the value in D column.
1) if "D" column value is "High" then bodycontent1 should be selected
2) if "D" column value is "Medium" then bodycontent2 should be selected
3) if "D" column value is "Low" then bodycontent3 should be selected
The below code just picks the bodycontent1 for any criteria.
Code:
Option Explicit
Public Sub Example()
Dim olApp As Outlook.Application
Dim olNs As Outlook.Namespace
Dim Inbox As Outlook.MAPIFolder
Dim Item As Variant
Dim MsgFwd As MailItem
Dim Items As Outlook.Items
Dim Email As String
Dim Email1 As String
Dim ItemSubject As String
Dim lngCount As Long
Dim i As Long
Dim RecipTo As Recipient
Dim RecipCC As Recipient
Dim RecipBCC As Recipient
Dim onbehalf As Variant
Dim EmailBody As String
Dim BodyName As String
Dim Bodycontent1 As String
Dim Bodycontent2 As String
Dim Bodycontent3 As String
Dim Criteria1 As String
Set olApp = CreateObject("Outlook.Application")
Set olNs = olApp.GetNamespace("MAPI")
Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
Set Items = Inbox.Items
i = 2 ' i = Row 2
With Worksheets("Sheet1") ' Sheet Name
Do Until IsEmpty(.Cells(i, 1))
ItemSubject = .Cells(i, 1).Value '(i, 1) = (Row 2,Column 1)
Email = .Cells(i, 16).Value '(i, 2) = (Row 2,Column 2)
Email1 = .Cells(i, 2).Value
Criteria1 = .Cells(i, 4).Value
Bodycontent1 = "Hello this is for testing purpose1" & "<BR>" & _
"Regards," & "<BR>" & _
"Kelvin"
Bodycontent2 = "Hello this is for testing purpose2" & "<BR>" & _
"Regards," & "<BR>" & _
"Kelvin"
Bodycontent3 = "Hello this is for testing purpose3" & "<BR>" & _
"Regards," & "<BR>" & _
"Kelvin"
'// Loop through Inbox Items backwards
For lngCount = Items.Count To 1 Step -1
Set Item = Items.Item(lngCount)
If Item.Subject = ItemSubject Then ' if Subject found then
Set MsgFwd = Item.Forward
Set RecipTo = MsgFwd.Recipients.Add(Email1)
Set RecipTo = MsgFwd.Recipients.Add("secnww#hp.com")
Set RecipBCC = MsgFwd.Recipients.Add(Email)
MsgFwd.SentOnBehalfOfName = "doc#hp.com"
BodyName = .Cells(i, 3).Value
RecipTo.Type = olTo
RecipBCC.Type = olBCC
Debug.Print Item.Body
If Criteria1 = "high" Then
MsgFwd.HTMLBody = Bodycontent1 & Item.HTMLBody
ElseIf Criteria1 = "medium" Then
MsgFwd.HTMLBody = Bodycontent2 & Item.HTMLBody
Else 'If Criteria1 = "Low" Then
MsgFwd.HTMLBody = Bodycontent3 & Item.HTMLBody
MsgFwd.Display
End If
End If
Next ' exit loop
i = i + 1 ' = Row 2 + 1 = Row 3
Loop
End With
Set olApp = Nothing
Set olNs = Nothing
Set Inbox = Nothing
Set Item = Nothing
Set MsgFwd = Nothing
Set Items = Nothing
MsgBox "Mail sent"
End Sub
You should use Select Case rather than If/ElseIf
See the part about LastRow which is clear than Loop+i=i+1
I've added an Exit For (commented), in case you want to gain time, and only forward the 1st message with the subject you're looking for!
Final code :
Option Explicit
Public Sub Example()
Dim olApp As Outlook.Application
Dim olNs As Outlook.NameSpace
Dim Inbox As Outlook.MAPIFolder
Dim Item As Variant
Dim MsgFwd As MailItem
Dim wS As Worksheet
Dim Items As Outlook.Items
Dim Email As String
Dim Email1 As String
Dim ItemSubject As String
Dim lngCount As Long
Dim LastRow As Long
Dim i As Long
Dim BodyName As String
Dim Bodycontent1 As String
Dim Bodycontent2 As String
Dim Bodycontent3 As String
Dim Criteria1 As String
Set olApp = CreateObject("Outlook.Application")
Set olNs = olApp.GetNamespace("MAPI")
Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
Set Items = Inbox.Items
Bodycontent1 = "Hello this is for testing purpose1" & "<BR>" & _
"Regards," & "<BR>" & _
"Kelvin"
Bodycontent2 = "Hello this is for testing purpose2" & "<BR>" & _
"Regards," & "<BR>" & _
"Kelvin"
Bodycontent3 = "Hello this is for testing purpose3" & "<BR>" & _
"Regards," & "<BR>" & _
"Kelvin"
Set wS = thisworkbook.Worksheets("Sheet1") ' Sheet Name
With wS
LastRow = .Range("A" & .rows.Count).End(xlup).Row
For i = 2 To LastRow
ItemSubject = .Cells(i, 1).value
Email = .Cells(i, 16).value
Email1 = .Cells(i, 2).value
Criteria1 = .Cells(i, 4).value
BodyName = .Cells(i, 3).value
'// Loop through Inbox Items backwards
For lngCount = Items.Count To 1 Step -1
Set Item = Items.Item(lngCount)
If Item.Subject <> ItemSubject Then
Else
'If Subject found then
Set MsgFwd = Item.Forward
With MsgFwd
.To = Email1 & " ; secnww#hp.com"
.BCC = Email
.SentOnBehalfOfName = "doc#hp.com"
Select Case LCase(Criteria1)
Case Is = "high"
.HTMLBody = Bodycontent1 & Item.HTMLBody
Case Is = "medium"
.HTMLBody = Bodycontent2 & Item.HTMLBody
Case Is = "low"
.HTMLBody = Bodycontent3 & Item.HTMLBody
Case Else
MsgBox "Criteria : " & Criteria1 & " not recognised!", _
vbCritical + vbOKOnly, "Case not handled"
End Select
.Display
'Exit For
End With 'MsgFwd
End If
Next lngCount
Next i
End With 'wS
Set olApp = Nothing
Set olNs = Nothing
Set Inbox = Nothing
Set Item = Nothing
Set MsgFwd = Nothing
Set Items = Nothing
MsgBox "Mail sent"
End Sub
I have the following problem. I use MSword mail merge to send emails. I regularly send out 100-500 emails (not spam, singular requests). I keep my email addresses in a single MSexcel sheet. Many of the email addresses are broken, and most replies are negative. Many of the emails responses come within the first 30 minutes of sending the email. After I get a response, I need to mark the response on the excel list. This process can be time consuming. Thus, the problem. Now, the question.
Is there a way to make my computer check the subject line of my emails for a specified string, and if it contains that string, then it copies the email address from that email, either in the body of the email, or in the sender field, and then moves to a specified excel sheet, searches for the email address in the excel sheet, and then marks the email address in the excel sheet.
Very happy for anyone that can point me in the right direction. I have absolutely no programming experience. I have used computers my entire life, but mostly to send and receive emails, or browse the internet.
You can use this directly from Excel, it's a bit overkill for what you want but you can remove fields if you don't need them:
'*********************************************************************************************
' All code is supplied under the Creative Commons License (CC). Code samples provided by
' Wilde XL Solutions are strictly for non-commerical use only and provided for the purpose
' learning and study. If you would like to seek permission to use this code in any way other
' than specified in this license agreement, please email cc#wxls.co.uk.
'
' A copy of the general creative commons (CC) license can be found at:
' http://tinyurl.com/WXLSCCinfo
'*********************************************************************************************
Sub getMail()
' This sub is designed to be used with a blank worksheet. It will create the header
' fields as required, and continue to populate the email data below the relevant header.
' Declare required variables
'-------------------------------------------------------------
Dim olApp As Object
Dim olFolder As Object
Dim olMailItem As Object
Dim strTo As String
Dim strFrom As String
Dim dateSent As Variant
Dim dateReceived As Variant
Dim strSubject As String
Dim strBody As String
Dim loopControl As Variant
Dim mailCount As Long
Dim totalItems As Long
'-------------------------------------------------------------
'Turn off screen updating
Application.ScreenUpdating = False
'Setup headers for information
Range("A1:F1").Value = Array("To", "From", "Subject", "Body", "Sent (from Sender)", "Received (by Recipient)")
'Format columns E and F to
Columns("E:F").EntireColumn.NumberFormat = "DD/MM/YYYY HH:MM:SS"
'Create instance of Outlook
Set olApp = CreateObject("Outlook.Application")
'Select folder to extract mail from
Set olFolder = olApp.GetNamespace("MAPI").PickFolder
'Get count of mail items
totalItems = olFolder.items.Count
mailCount = 0
'Loop through mail items in folder
For Each loopControl In olFolder.items
'If loopControl is a mail item then continue
If TypeName(loopControl) = "MailItem" Then
'Increase mailCount
mailCount = mailCount + 1
'Inform user of item count in status bar
Application.StatusBar = "Reading email no. " & mailCount & " of " & totalItems
'Get mail item
Set olMailItem = loopControl
'Get Details
With olMailItem
strTo = .To
'If strTo begins with "=" then place an apostrophe in front to denote text format
If Left(strTo, 1) = "=" Then strTo = "'" & strTo
strFrom = .Sender
'If sender displays name only, show name followed by email address e.g.(Bloggs, Joe < j.bloggs#mail.com >)
If InStr(1, strFrom, "#") < 1 Then strFrom = strFrom & " - < " & .SenderEmailAddress & " >"
dateSent = .SentOn
dateReceived = .ReceivedTime
strSubject = .Subject
strBody = .Body
End With
'Place information into spreadsheet
'import information starting from last blank row in column A
With Range("A" & Rows.Count).End(xlUp).Offset(0, 0)
.Value = strTo
.Offset(1, 1).Value = strFrom
.Offset(2, 2).Value = strSubject
'Check for previous replies by looking for "From:" in the body text
'Check for the word "From:"
If InStr(0, strBody, "From:") > 0 Then
'If exists, copy start of email body, up to the position of "From:"
.Offset(1, 1).Value = Mid(strBody, 1, InStr(1, strBody, "From:") - 1)
Else
'If doesn't exist, copy entire mail body
.Offset(3, 3).Value = strBody
End If
.Offset(4, 4).Value = dateSent
.Offset(5, 5).Value = dateReceived
End With
'Release item from memory
Set olMailItem = Nothing
End If
'Next Item
Next loopControl
'Release items from memory
Set olFolder = Nothing
Set olApp = Nothing
'Resume screen updating
Application.ScreenUpdating = True
'reset status bar
Application.StatusBar = False
'Inform user that code has finished
MsgBox mailCount & " messages copied successfully.", vbInformation, "Complete"
End Sub