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

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.
Thread starter Similar threads Forum Replies Date
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
L Macro/VBA to Reply All, with the original attachments Outlook VBA and Custom Forms 2
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
C How to use VBA to show only items x days old or more Outlook VBA and Custom Forms 1
B VBA to convert email to task, insert text of email in task notes, and attach copy of original email Outlook VBA and Custom Forms 4
D Outlook VBA error extracting property data from GetRules collection Outlook VBA and Custom Forms 10
S Reference Custom Fields with VBA Outlook VBA and Custom Forms 2
PGSystemTester VBA To Change AppointmentItem.BusyStatus From MeetingItem Before Send Using Outlook 0
A VBA macro for 15 second loop in send and received just for 1 specific mailbox Outlook VBA and Custom Forms 1
O Email not leaving Outbox when using Excel VBA to sync Outlook account Outlook VBA and Custom Forms 4
G VBA Macro Calendar Printing Assistant 4
R Help Revising VBA macro to delete email over different time span Outlook VBA and Custom Forms 0
B VBA to Collapse Task Folder Groups Outlook VBA and Custom Forms 1
R Expand VBA Permanent Delete Code Outlook VBA and Custom Forms 6
shrydvd vba to secure zip attachments Outlook VBA and Custom Forms 3
M Adding Subject to this Link-Saving VBA Outlook VBA and Custom Forms 5
N VBA to delete duplicates by message-id on common pst for 2 or more emails Outlook VBA and Custom Forms 0
S Change VBA script to send HTML email instead of text Outlook VBA and Custom Forms 3
M VBA to auto forward message with new subject and body text Outlook VBA and Custom Forms 8
A Custom VBA to sort emails into folders Outlook VBA and Custom Forms 0
L Moving emails with similar subject and find the timings between the emails using outlook VBA macro Outlook VBA and Custom Forms 1
B Outlook Business Contact Manager with SQL to Excel, User Defined Fields in BCM don't sync in SQL. Can I use VBA code to copy 1 field to another? BCM (Business Contact Manager) 0
R VBA for copying sent email to current folder under a shared mailbox Outlook VBA and Custom Forms 17
A Edit subject - and change conversationTopic - using VBA and redemption Outlook VBA and Custom Forms 2
N How can I increase/faster outlook VBA Macro Speed ? Using Outlook 2
N Outlook Email Rule execution through shortcut keys (VBA codes) Using Outlook 1
A VBA Code in Outlook disappears after first use Outlook VBA and Custom Forms 1
B Clear Offline Items (Mail Folder) via VBA Outlook VBA and Custom Forms 1
dweller Outlook 2010 Rule Ignores VBA Script Outlook VBA and Custom Forms 2
D.Moore Folder view settings by VBA macro Outlook VBA and Custom Forms 57
F VBA to ensure a code is entered in Subject title Outlook VBA and Custom Forms 1
B Vba to monitor time to respond to emails using a shared mailbox Outlook VBA and Custom Forms 5
N VBA Script to Open highlighted e-mail and Edit Message Outlook VBA and Custom Forms 5
G Outlook VBA and Google Calendar ("Events") Outlook VBA and Custom Forms 1
B Looking to get the Recipient email address (or even the "friendly name") from an email I am replying to using VBA Outlook VBA and Custom Forms 4
J VBA Outlook : Subject line : Cut and Paste name to heading , number to very end of the body of Email Outlook VBA and Custom Forms 1
M VBA to send reminder email if no response Using Outlook 13
Similar threads


















































Top