VBA to extract email (fields and body) to Excel

Status
Not open for further replies.

Outlook Rookie

Senior Member
Outlook version
Outlook 2013 64 bit
Email Account
Exchange Server
Hi All,

I receive routine confirmation messages with details and want to extract some of the text into Excel.
Can I please have a VBA script that copies the key information (please see sample) and pastes it in a specified workbook (please see sample).
There is a lot more information in the email, but I only need some related info.
I’ve attached two sample files. One of the email, and the other of a workbook where I want the information to be pasted. This is a running record, so the information should be pasted into the next available row.
I am using MS 2007 Excel and Outlook.
Can anyone assist me please? Please make your instructions as detailed as possible (as I am not very technical).
Thank you.
OR
 

Attachments

  • Sample Email for export to Excel.pdf
    90.7 KB · Views: 651
  • Sample Workbook for Outlook VBA to export email details to Excel workbook.pdf
    84.3 KB · Views: 571

Outlook Rookie

Senior Member
Outlook version
Outlook 2013 64 bit
Email Account
Exchange Server
See Use a macro to copy data in Outlook email to Excel workbook - this is used in a run a script rule.

Use RegEx to extract text from an Outlook email message - the second macro on this page shows how to get multiple values.
Hi Diane,
Thank you for your fast replies.
I tried the codes but came up with Compile error: Ambiguous name detected: CopyToExcel.
Also, since I am really very basic with code, please post detailed instructions. There are other saved macros fyi.
Thanks,
OR
 

Diane Poremsky

Senior Member
Outlook version
Outlook 2016 32 bit
Email Account
Office 365 Exchange
This: Compile error: Ambiguous name detected: CopyToExcel. means you have two macros with the same name. Add a 2 to the end of this one to fix the error.
 

Outlook Rookie

Senior Member
Outlook version
Outlook 2013 64 bit
Email Account
Exchange Server
This: Compile error: Ambiguous name detected: CopyToExcel. means you have two macros with the same name. Add a 2 to the end of this one to fix the error.

I'm now getting a Compile error: Invalid inside procedure at the Option Explicit.. :(
 

Diane Poremsky

Senior Member
Outlook version
Outlook 2016 32 bit
Email Account
Office 365 Exchange
post the code you are using. That error usually means there is a problem with the way a global variable is set.
 

Outlook Rookie

Senior Member
Outlook version
Outlook 2013 64 bit
Email Account
Exchange Server
post the code you are using. That error usually means there is a problem with the way a global variable is set.

Please note the brackets to indicate that the path/folder/file is included there

CopyToExcel code sample


Option Explicit

Private Const xlUp As Long = -4162


Sub CopyToExcel(olItem As Outlook.MailItem)

Dim xlApp As Object

Dim xlWB As Object

Dim xlSheet As Object

Dim vText, vText2, vText3, vText4, vText5 As Variant

Dim sText As String

Dim rCount As Long

Dim bXStarted As Boolean

Dim enviro As String

Dim strPath As String

Dim Reg1 As Object

Dim M1 As Object

Dim M As Object


enviro = CStr(Environ("USERPROFILE"))

'the path of the workbook

strPath = enviro & “the Path is entered here "

On Error Resume Next

Set xlApp = GetObject(, "Excel.Application")

If Err <> 0 Then

Application.StatusBar = "Please wait while Excel source is opened ... "

Set xlApp = CreateObject("Excel.Application")

bXStarted = True

End If

On Error GoTo 0

'Open the workbook to input the data

Set xlWB = xlApp.Workbooks.Open(strPath)

Set xlSheet = xlWB.Sheets("Test")

Set olItem = Application.ActiveExplorer().Selection(1)

'Find the next empty line of the worksheet

rCount = xlSheet.Range("B" & xlSheet.Rows.Count).End(xlUp).Row

rCount = rCount + 1


sText = olItem.Body


Set Reg1 = CreateObject("VBScript.RegExp")

' \s* = invisible spaces

' \d* = match digits

' \w* = match alphanumeric


With Reg1

.Pattern = "((P130\w*)\s*(\w*)\s*(\w*)\s*(\w*)\s*([\d-\.]*))"

End With

If Reg1.test(sText) Then


' each "(\w*)" and the "(\d)" are assigned a vText variable

Set M1 = Reg1.Execute(sText)

For Each M In M1

vText = Trim(M.SubMatches(1))

vText2 = Trim(M.SubMatches(2))

vText3 = Trim(M.SubMatches(3))

vText4 = Trim(M.SubMatches(4))

vText5 = Trim(M.SubMatches(5))

Next

End If


xlSheet.Range("B" & rCount) = vText

xlSheet.Range("c" & rCount) = vText2

xlSheet.Range("d" & rCount) = vText3

xlSheet.Range("e" & rCount) = vText4

xlSheet.Range("f" & rCount) = vText5


xlWB.Close 1

If bXStarted Then

xlApp.Quit

End If

Set M = Nothing

Set M1 = Nothing

Set Reg1 = Nothing

Set xlApp = Nothing

Set xlWB = Nothing

Set xlSheet = Nothing

End Sub
 

Diane Poremsky

Senior Member
Outlook version
Outlook 2016 32 bit
Email Account
Office 365 Exchange
it might be nothing (but goofiness here), but make sure the quote is correct on the path line - it needs to be a straight quote on the left, not the "smart quote".
strPath = enviro & “the Path is entered here "
 

Outlook Rookie

Senior Member
Outlook version
Outlook 2013 64 bit
Email Account
Exchange Server
Hi Diane,

Thank you for replying.
I worked on the code as below, with only trial and error and no, repeat, no VBA knowledge.

Basically, what I need is this. For a specific Outlook message (not all the messages in a folder/Inbox), when I run the code it should open a specific Excel file (path specified), and enter the fields in the next available row AFTER the title or header fields. The row titles should not be repeated, just the corresponding entries and so I have a log in Excel of related messages.
The code below gives me a “Compile Error: Expected Array” at this line
If Not (olItems(x).Subject, at the “olItems(x) portion.
Can you please help me with this?
OR



Option Explicit

Sub CopyToExcel()

Dim xlApp As Object

Dim xlWB As Object

Dim xlSheet As Object

Dim rCount As Long

Dim bXStarted As Boolean

Dim enviro As String

Dim strPath As String


Dim currentExplorer As Explorer

Dim Selection As Selection

Dim olItem As Outlook.MailItem

Dim obj As Object

Dim strColB, strColC, strColD, strColE, strColF As String



' Get Excel set up

enviro = CStr(Environ("USERPROFILE"))

'the path of the workbook

strPath = enviro & "path will be here"

On Error Resume Next

Set xlApp = GetObject(, "Excel.Application")

If Err <> 0 Then

Application.StatusBar = "Please wait while Excel source is opened ... "

Set xlApp = CreateObject("Excel.Application")

bXStarted = True

End If

On Error GoTo 0

'Open the workbook to input the data

Set xlWB = xlApp.Workbooks.Open("path will be here")

Set xlSheet = xlWB.Sheets("Test1")

' Process the message record


On Error Resume Next

'Find the next empty line of the worksheet

rCount = xlSheet.Range("B" & xlSheet.Rows.Count).End(-4162).Row



' get the values from outlook

Set currentExplorer = Application.ActiveExplorer

Set Selection = currentExplorer.Selection

For Each obj In Selection


Set olItem = obj


'collect the fields

strColB = olItem.SenderName

strColC = olItem.SenderEmailAddress

strColD = olItem.Body

strColE = olItem.To

strColF = olItem.ReceivedTime


'write them in the excel sheet


On Error Resume Next

x = 2

arrHeaders = Array("Date Created", "Date Received", "Subject", "Sender", "Sender's Email", "CC", "Sender's Email Type", "Message Size", "Unread?")


xlWB.Worksheets(1).Range("A1").Resize(1, UBound(arrHeaders)).Value = ""


Do

With xlWB.Worksheets(1)

If Not (olItems(x).Subject = "" And olItems(x).CreationTime = "") Then

Range("A1").Resize(1, UBound(arrHeaders) + 1) = arrHeaders

Cells(x, 1).Value = olItems(x).CreationTime

Cells(x, 2).Value = olItems(x).ReceivedTime

Cells(x, 3).Value = olItems(x).Subject

Cells(x, 4).Value = olItems(x).SenderName

Cells(x, 5).Value = olItems(x).SenderEmailAddress

Cells(x, 6).Value = olItems(x).CC

Cells(x, 7).Value = olItems(x).SenderEmailType 'Ex: Internal server; SMTP or SMFP? Internet Server

Cells(x, 8).Value = Format((olItems(x).Size / 1024) / 1024, "#,##0.00") & "MB"

Cells(x, 9).Value = olItems(x).CreationTime

x = x + 1

End If

End With


Set olItem = Nothing

Set obj = Nothing

Set currentExplorer = Nothing

Set xlApp = Nothing

Set xlWB = Nothing

Set xlSheet = Nothing

End Sub
 

Diane Poremsky

Senior Member
Outlook version
Outlook 2016 32 bit
Email Account
Office 365 Exchange
I'm not sure why the array error, you're setting x = 2 - the rows should be rCount:

'Find the next empty line of the worksheet
rCount = xlSheet.Range("B" & xlSheet.Rows.Count).End(-4162).Row

So you'd use
Cells(rCount, 1).Value = ....

Then remove this line:
arrHeaders = Array("Date Created", "Date Received", "Subject", "Sender", "Sender's Email", "CC", "Sender's Email Type", "Message Size", "Unread?")
and this:
Range("A1").Resize(1, UBound(arrHeaders) + 1) = arrHeaders


You're also using X to identify the item: olItems(x).
The values were set earlier:
strColB = olItem.SenderName
strColC = olItem.SenderEmailAddress
strColD = olItem.Body
strColE = olItem.To
strColF = olItem.ReceivedTime

use either of these formats instead:
Cells(x, 1).Value = olItem.CreationTime
Cells(x, 2).Value = strColF
 

Outlook Rookie

Senior Member
Outlook version
Outlook 2013 64 bit
Email Account
Exchange Server
Hi Diane,

Thank you again for your help.

Sorry, I tried to understand your message as best I could and made the corrections below. I was getting a syntax error and found that I had to remove olItems and replace it with a singular “olItem”.

Now I am getting the Compile Error: Do Without Loop at the End Sub


Can you please fix the code?

Thank you.


Option Explicit

Sub CopyToExcel()

Dim xlApp As Object

Dim xlWB As Object

Dim xlSheet As Object

Dim rCount As Long

Dim bXStarted As Boolean

Dim enviro As String

Dim strPath As String


Dim currentExplorer As Explorer

Dim Selection As Selection

Dim olItem As Outlook.MailItem

Dim obj As Object

Dim strColB, strColC, strColD, strColE, strColF As String



' Get Excel set up

enviro = CStr(Environ("USERPROFILE"))

'the path of the workbook

strPath = enviro & "\\RC14dp13\LDS\Staff Folders\Yola Rego\usb\Excel\Excel and VBA\VBA Outlook\20160425 Cafeteria Orders Consolidated.xlsx"

On Error Resume Next

Set xlApp = GetObject(, "Excel.Application")

If Err <> 0 Then

Application.StatusBar = "Please wait while Excel source is opened ... "

Set xlApp = CreateObject("Excel.Application")

bXStarted = True

End If

On Error GoTo 0

'Open the workbook to input the data

Set xlWB = xlApp.Workbooks.Open("path will be here")

Set xlSheet = xlWB.Sheets("Test1")

' Process the message record


On Error Resume Next

'Find the next empty line of the worksheet

rCount = xlSheet.Range("B" & xlSheet.Rows.Count).End(-4162).Row



' get the values from outlook

Set currentExplorer = Application.ActiveExplorer

Set Selection = currentExplorer.Selection

For Each obj In Selection


Set olItem = obj


'collect the fields

Cells(x, 1).Value = olItem.SenderName

Cells(x, 1).Value = olItem.SenderEmailAddress

Cells(x, 1).Value = olItem.Body

Cells(x, 1).Value = olItem.To

Cells(x, 1).Value = olItem.ReceivedTime


'write them in the excel sheet


On Error Resume Next

x = 2


xlWB.Worksheets (1)


Do

With xlWB.Worksheets(1)

If Not (olItem(x).Subject = "" And olItem(x).CreationTime = "") Then

Cells(x, 1).Value = olItem(x).CreationTime

Cells(x, 2).Value = olItem(x).ReceivedTime

Cells(x, 3).Value = olItem(x).Subject

Cells(x, 4).Value = olItem(x).SenderName

Cells(x, 5).Value = olItem(x).SenderEmailAddress

Cells(x, 6).Value = olItem(x).CC

Cells(x, 7).Value = olItem(x).SenderEmailType 'Ex: Internal server; SMTP or SMFP? Internet Server

Cells(x, 8).Value = Format((olItem(x).Size / 1024) / 1024, "#,##0.00") & "MB"

Cells(x, 9).Value = olItem(x).CreationTime

x = x + 1

End If

End With


Set olItem = Nothing

Set obj = Nothing

Set currentExplorer = Nothing

Set xlApp = Nothing

Set xlWB = Nothing

Set xlSheet = Nothing

End Sub
 

Diane Poremsky

Senior Member
Outlook version
Outlook 2016 32 bit
Email Account
Office 365 Exchange
The error is tell you that you have a Do but no corresponding Loop at the end (after the end with. )

It looks there are other errors -

This is telling strpath that it's c:\users\username\\RC14dp13\LDS...

strPath = enviro & "\\RC14dp13\LDS\Staff Folders\Yola Rego\usb\Excel\Excel and VBA\VBA Outlook\20160425 Cafeteria Orders Consolidated.xlsx"

Assuming \\RC14dp13\ is a shared server, remove the enviro part:
strPath = "\\RC14dp13\LDS\Staff Folders\Yola Rego\usb\Excel\Excel and VBA\VBA Outlook\20160425 Cafeteria Orders Consolidated.xlsx"


this should use the strpath you set above:
Set xlWB = xlApp.Workbooks.Open(strpath)


I'm not sure what this is supposed to do:
Cells(x, 1).Value = olItem.SenderName
Cells(x, 1).Value = olItem.SenderEmailAddress
Cells(x, 1).Value = olItem.Body
Cells(x, 1).Value = olItem.To
Cells(x, 1).Value = olItem.ReceivedTime


since you also have this:
Cells(x, 1).Value = olItem(x).CreationTime
Cells(x, 2).Value = olItem(x).ReceivedTime
Cells(x, 3).Value = olItem(x).Subject
Cells(x, 4).Value = olItem(x).SenderName
Cells(x, 5).Value = olItem(x).SenderEmailAddress
Cells(x, 6).Value = olItem(x).CC
Cells(x, 7).Value = olItem(x).SenderEmailType 'Ex: Internal server; SMTP or SMFP? Internet Server
Cells(x, 8).Value = Format((olItem(x).Size / 1024) / 1024, "#,##0.00") & "MB"
Cells(x, 9).Value = olItem(x).CreationTime


If you need to keep adding to the same sheet, use rCount - it identifies the last used cell and starts there.

Cells(rCount, 1).Value = olItem(x).CreationTime
Cells(rCount, 2).Value = olItem(x).ReceivedTime
Cells(rCount, 3).Value = olItem(x).Subject
Cells(rCount, 4).Value = olItem(x).SenderName
Cells(rCount, 5).Value = olItem(x).SenderEmailAddress
Cells(rCount, 6).Value = olItem(x).CC
Cells(rCount, 7).Value = olItem(x).SenderEmailType 'Ex: Internal server; SMTP or SMFP? Internet Server
Cells(rCount, 8).Value = Format((olItem(x).Size / 1024) / 1024, "#,##0.00") & "MB"
Cells(rCount, 9).Value = olItem(x).CreationTime
 

Outlook Rookie

Senior Member
Outlook version
Outlook 2013 64 bit
Email Account
Exchange Server
Hi Diane,
Thank you for the revisions. Sorry for the delay in my response and I will try them soon.
BTW, I sent a couple of messages to the Forum Administrators and have not heard back. Are you able to contact them or check for me, please?
OR
 

Outlook Rookie

Senior Member
Outlook version
Outlook 2013 64 bit
Email Account
Exchange Server
Hi Diane,
Can you please advise the forum administrator to respond to my message sent via contact me
 
Status
Not open for further replies.
Similar threads
Thread starter Title Forum Replies Date
T vba extract data from msg file as attachment file of mail message Outlook VBA and Custom Forms 1
D VBA Script to extract text matching specific criteria Outlook VBA and Custom Forms 1
M VBA Code to extract data from an Outlook Form Using Outlook 0
M add new attendee to existing meetings with VBA Outlook VBA and Custom Forms 5
D VBA code to select a signature from the signatures list Outlook VBA and Custom Forms 3
D Create advanced search (email) via VBA with LONG QUERY (>1024 char) Outlook VBA and Custom Forms 2
David McKay VBA to manually forward using odd options Outlook VBA and Custom Forms 1
FryW Need help modifying a VBA script for in coming emails to auto set custom reminder time Outlook VBA and Custom Forms 0
S vba outlook search string with special characters Outlook VBA and Custom Forms 1
S VBA search string with special characters Outlook VBA and Custom Forms 1
U Outlook 2019 VBA run-time error 424 Outlook VBA and Custom Forms 2
DDB VBA to Auto Insert Date and Time in the signature Outlook VBA and Custom Forms 2
F VBA to move email from Non Default folder to Sub folders as per details given in excel file Outlook VBA and Custom Forms 11
G VBA to save selected Outlook msg with new name in selected network Windows folder Outlook VBA and Custom Forms 1
F Excel VBA to move mails for outlook 365 on secondary mail account Outlook VBA and Custom Forms 1
B Zoom automatically next email item (VBA) Outlook VBA and Custom Forms 2
K Outlook Office 365 VBA download attachment Outlook VBA and Custom Forms 2
A VBA Script - Print Date between first email in Category X and last email in Category Y Outlook VBA and Custom Forms 3
N Help creating a VBA macro with conditional formatting to change the font color of all external emails to red Outlook VBA and Custom Forms 5
N Save selected messages VBA does not save replies and/or messages that contain : in subject Outlook VBA and Custom Forms 1
Y Filter unread emails in a search folder vba help Outlook VBA and Custom Forms 0
V vBA for searching a cell's contents in Outlook and retrieving the subject line Outlook VBA and Custom Forms 1
B vBA for exporting excel file from outlook 2016 Outlook VBA and Custom Forms 3
L Modifying VBA script to delay running macro Outlook VBA and Custom Forms 3
L Need help modifying a VBA script for emails stuck in Outbox Outlook VBA and Custom Forms 6
K can't get custom form to update multiple contacts using VBA Outlook VBA and Custom Forms 3
S Excel vba code to manage outlook web app Using Outlook 10
H Custom Outlook Contact Form VBA Outlook VBA and Custom Forms 1
S Problem Checking the available stores in my Inbox (Outlook VBA) Outlook VBA and Custom Forms 0
S Outlook VBA How to adapt this code for using in a different Mail Inbox Outlook VBA and Custom Forms 0
S Add VBA save code Using Outlook 0
C Auto Run VBA Code on new email Outlook VBA and Custom Forms 1
O VBA Cases with Listbox - Can you use Multi-Select? Outlook VBA and Custom Forms 4
O VBA Outlook Message Attachment - Array Index Out of Bounds Outlook VBA and Custom Forms 0
V Modifying the built in forms with VBA Outlook VBA and Custom Forms 4
S Excel VBA and shared calendar issue Outlook VBA and Custom Forms 3
L Macro/VBA to Reply All, with the original attachments Outlook VBA and Custom Forms 3
L VBA unknown character Outlook VBA and Custom Forms 2
G Move tasks up/down todo list by VBA Outlook VBA and Custom Forms 1
diver864 vba for a rule to automatically accept meeting requests with 'vacation' in subject, change to all-day event, change to free, don't send reply Outlook VBA and Custom Forms 1
K Use VBA to find Sender and Recipient from Microsfot 365 Journaled Email Items Outlook VBA and Custom Forms 3
J Want to learn VBA Macros for Outlook. What book can you recommend? Outlook VBA and Custom Forms 2
F VBA code to dock Styles whenever I write or edit an email Outlook VBA and Custom Forms 0
C VBA to prompt for Sent folder destination Outlook VBA and Custom Forms 3
B Adding signature to bottom of VBA reply email Outlook VBA and Custom Forms 1
B Change Font and Font size using VBA Outlook VBA and Custom Forms 9
M Outlook 2013 reminder email by using Outlook vba Outlook VBA and Custom Forms 2
D.Moore VBA script fail after Office 365 update Using Outlook 8
R Limiting length of saved attachment in VBA Outlook VBA and Custom Forms 2
S Skype for business meeting vba code Outlook VBA and Custom Forms 1

Similar threads

Top