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

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
 
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.. :(
 
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
 
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 "
 
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
 
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
 
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
 
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
 
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
 
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
C VBA in "New Outlook?" Using Outlook 0
efire9207 VBA Outlook Contacts Outlook VBA and Custom Forms 6
B Requesting VBA code to make Outlook prompt for confirmation when deleting a task? Outlook VBA and Custom Forms 4
M Outlook 365 VBA Auto-Forward Only the first of Duplicate Emails Outlook VBA and Custom Forms 2
N VBA Code Not Working correctly Outlook VBA and Custom Forms 1
L VBA to Triage Incoming Email Outlook VBA and Custom Forms 0
J Outlook VBA to send from Non-default Account & Data Files Outlook VBA and Custom Forms 4
H using VBA to edit subject line Outlook VBA and Custom Forms 0
G Get current open draft message body from VBA Outlook VBA and Custom Forms 1
P VBA to add email address to Outlook 365 rule Outlook VBA and Custom Forms 0
M Outlook 2016 outlook vba to look into shared mailbox Outlook VBA and Custom Forms 0
V VBA Categories unrelated to visible calendar and Visual appointment Categories Outlook VBA and Custom Forms 2
D Outlook VBA forward the selected email to the original sender’s email ID (including the email used in TO, CC Field) from the email chain Outlook VBA and Custom Forms 2
R Outlook 365 VBA AUTO SEND WITH DELAY FOR EACH EMAIL Outlook VBA and Custom Forms 0
R Outlook 2019 VBA to List Meetings in Rooms Outlook VBA and Custom Forms 0
geoffnoakes Counting and/or listing fired reminders via VBA Using Outlook 1
O VBA - Regex - remove double line spacing Outlook VBA and Custom Forms 1
D.Moore Strange VBA error Outlook VBA and Custom Forms 4
B Modify VBA to create a RULE to block multiple messages Outlook VBA and Custom Forms 0
D Outlook 2021 Using vba code to delete all my spamfolders not only the default one. Outlook VBA and Custom Forms 0
K vba code to auto download email into a specific folder in local hard disk as and when any new email arrives in Inbox/subfolder Outlook VBA and Custom Forms 0
D VBA - unable to set rule condition 'on this computer only' Outlook VBA and Custom Forms 5
L Fetch, edit and forward an email with VBA outlook Outlook VBA and Custom Forms 2
BartH VBA no longer working in Outlook Outlook VBA and Custom Forms 1
W Can vba(for outlook) do these 2 things or not? Outlook VBA and Custom Forms 2
MattC Changing the font of an email with VBA Outlook VBA and Custom Forms 1
P MailItem.To Property with VBA not work Outlook VBA and Custom Forms 2
P Tweak vba so it can target another mailbox Outlook VBA and Custom Forms 1
A Outlook 2010 VBA fails to launch Outlook VBA and Custom Forms 2
richardwing Outlook 365 VBA to access "Other Actions" menu for incoming emails in outlook Outlook VBA and Custom Forms 0
W Create a Quick Step or VBA to SAVE AS PDF in G:|Data|Client File Outlook VBA and Custom Forms 1
J Outlook Rules VBA Run a Script - Multiple Rules Outlook VBA and Custom Forms 0
C Outlook (desktop app for Microsoft365) restarts every time I save my VBA? Using Outlook 1
D VBA Macro to Print and Save email to network location Outlook VBA and Custom Forms 1
TedSch Small vba to kill political email Outlook VBA and Custom Forms 3
E Outlook 365 Outlook/VBA Outlook VBA and Custom Forms 11
N VBA Macro To Save Emails Outlook VBA and Custom Forms 1
Z VBA Forward vs manual forward Outlook VBA and Custom Forms 2
J VBA Cannot programmatically input or change Value for User Defined field Using Outlook 1
J VBA for outlook to compare and sync between calendar Outlook VBA and Custom Forms 1
A Any way to force sort by/group by on search results with VBA? Outlook VBA and Custom Forms 1
E Default shape via VBA Outlook VBA and Custom Forms 4
A Change settings Send/receive VBA Outlook VBA and Custom Forms 0
Z Import Tasks from Access Using VBA including User Defined Fields Outlook VBA and Custom Forms 0
E Outlook VBA change GetDefaultFolder dynamically Outlook VBA and Custom Forms 6
justicefriends How to set a flag to follow up using VBA - for addressee in TO field Outlook VBA and Custom Forms 11
M add new attendee to existing meetings with VBA Outlook VBA and Custom Forms 5

Similar threads

Back
Top