VBA to extract email (fields and body) to Excel

Status
Not open for further replies.

Outlook Rookie

Senior Member
Outlook version
Outlook 2007
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 2007
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 2007
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 2007
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 2007
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 2007
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 2007
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 2007
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.
Top