Copy lines from email to Excel into specific array - excel

I am needing to copy some data from emails into a spreadsheet with a VBA, here is how the data is formatted in the email:
Items/Cost:
Item Description 1: $38.88
Quantity: 1
Item Description 2: $39.99
Quantity: 1
The Item Description is always different. Here is how I would like the output to be formatted when copied to Excel:
And here is my current code that I've tried:
Sub CopyToExcel()
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Dim xl
Dim olItem As Outlook.MailItem
Dim vText As Variant
Dim sText As String
Dim vItem As Variant
Dim i As Long
Dim rCount As Long
Dim bXStarted As Boolean
Dim rTime As Date
Const strPath As String = "C:\Tracking.xlsx" 'the path of the workbook
If Application.ActiveExplorer.Selection.Count = 0 Then
MsgBox "No Items selected!", vbCritical, "Error"
Exit Sub
EndIf
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("Sheet1")
xlWB.Sheets(1).Cells.Delete
'Process each selected record
rCount = xlSheet.UsedRange.Rows.Count
'cCount = xlSheet.UsedRange.Columns.Count
For Each olItem In Application.ActiveExplorer.Selection
sText = olItem.Body
rTime = Format(olItem.ReceivedTime, "mmmm d, yyyy")
vText = Split(sText, Chr(13))
'Find the next empty line of the worksheet
rCount = rCount + 1
'Check each line of text in the message body
For i = UBound(vText) To 0 Step -1
If InStr(vText(i), "Items/Cost:") Then
'ParseText = vText(i + 1) & vbCrLf
xlSheet.Range("A" & rCount) = Trim(vText(2))
vItem = Split(vText(4), Chr(58))
xlSheet.Range("B" & rCount) = Trim(vItem(1))
xlSheet.Range("A" & rCount + 1) = Trim(vText(6))
vItem = Split(vText(8), Chr(58))
xlSheet.Range("B" & rCount + 1) = Trim(vItem(1))
xlSheet.Range("A" & rCount + 2) = Trim(vText(10))
vItem = Split(vText(12), Chr(58))
xlSheet.Range("B" & rCount + 2) = Trim(vItem(1))
xlSheet.Range("A" & rCount + 3) = Trim(vText(14))
vItem = Split(vText(16), Chr(58))
xlSheet.Range("B" & rCount + 3) = Trim(vItem(1))
xlSheet.Range("A" & rCount + 4) = Trim(vText(18))
vItem = Split(vText(20), Chr(58))
xlSheet.Range("B" & rCount + 4) = Trim(vItem(1))
End If
Next i
xlWB.Save
Next olItem
Set xlApp = Nothing
Set xlWB = Nothing
Set xlSheet = Nothing
Set olItem = Nothing
End Sub
Also I'm no expert at VB so any help is greatly appreciated.
UPDATE:
I figured out how to extract it the way I want to but it's sloppy and not dynamic. Sometimes there are 2 items and sometimes 5, so i need it to be adaptable. Can someone help me clean it up by chance?

Try the following
Option Explicit
Sub EmailToCsv()
Dim olItem As Outlook.MailItem
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim vText As Variant
Dim sText As String
Dim vItem As Variant
Dim i As Long
Dim RowCount As Long
Dim xlStarted As Boolean
Dim FilePath As String
'// Update File location
FilePath = "C:\Temp\Tracking.xlsx"
'// Process Selections
If Application.ActiveExplorer.Selection.Count = 0 Then
MsgBox "No Items selected!", vbCritical, "Error"
Exit Sub
End If
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")
xlStarted = True
End If
On Error GoTo 0
'// Open the workbook to input the data
Set xlWB = xlApp.Workbooks.Open(FilePath)
Set xlSheet = xlWB.Sheets("Sheet1")
'// Process each selected record
For Each olItem In Application.ActiveExplorer.Selection
sText = olItem.Body
vText = Split(sText, Chr(13)) ' Chr(13)) carriage return
'// Find the next empty line of the worksheet
RowCount = xlSheet.Range("A" & xlSheet.Rows.Count).End(xlUp).Row
RowCount = RowCount + 1
'// Check each line of text in the message body
For i = UBound(vText) To 0 Step -1
'// Item Description 1
If InStr(1, vText(i), "Item Description 1:") > 0 Then
vItem = Split(vText(i), Chr(58)) ' Chr(58) ":"
xlSheet.Range("A" & RowCount) = "Item Description 1: " & Trim(vItem(1))
End If
'// Quantity
If InStr(1, vText(i), "Quantity:") > 0 Then
vItem = Split(vText(i), Chr(58))
xlSheet.Range("B" & RowCount) = Trim(vItem(1))
End If
'// Item Description 2
If InStr(1, vText(i), "Item Description 2:") > 0 Then
vItem = Split(vText(i), Chr(58))
xlSheet.Range("A" & RowCount + 1) = "Item Description 2: " & Trim(vItem(1))
End If
'// Quantity
If InStr(1, vText(i), "Quantity:") > 0 Then
vItem = Split(vText(i), Chr(58))
xlSheet.Range("B" & RowCount + 1) = Trim(vItem(1))
End If
Next i
Next olItem
'// SaveChanges & Close
xlWB.Close SaveChanges:=True
If xlStarted Then
xlApp.Quit
End If
Set xlApp = Nothing
Set xlWB = Nothing
Set xlSheet = Nothing
Set olItem = Nothing
End Sub

Related

For loop to output in multiple columns

I'm trying to parse Outlook emails into an Excel spreadsheet.
All of the "vText"s are being output in column B and not B through E.
Original email text:
Caller: First Last
Phone: 123-456-7890
For: Company Name - Address
City: Metropolis
MSGID: 3068749608
I extract the Caller, Phone and MSGID fields just fine, but parsing the Company Name hasn't worked. It randomly pastes the Phone or MSGID values into that column instead.
Option Explicit
Private Const xlUp As Long = -4162
Sub CopyAllMessagesToExcel()
Dim objOL As Outlook.Application
Dim objItems As Outlook.Items
Dim objFolder As Outlook.MAPIFolder
Dim 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
Dim OutlookNamespace As NameSpace
enviro = CStr(Environ("USERPROFILE"))
'the path of the workbook
strPath = enviro & "file path"
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("Sheet1")
'Find the next empty line of the worksheet
'rCount = xlSheet.Range("B" & xlSheet.Rows.Count).End(xlUp).Row 'original code
rCount = xlSheet.Range("A" & xlSheet.Rows.Count).End(xlUp).Row
rCount = rCount + 1
Set objOL = Outlook.Application
Set OutlookNamespace = objOL.GetNamespace("MAPI")
Set objFolder = OutlookNamespace.GetDefaultFolder(olFolderInbox).Folders("SubFolder").Folders("SubSubFolder")
Set objItems = objFolder.Items
For Each olItem In objItems
On Error Resume Next
With olItem
sText = olItem.Body
Set Reg1 = CreateObject("VBScript.RegExp")
' \s* = invisible spaces
' \d* = match digits
' \w* = match alphanumeric
Dim i As Integer
For i = 1 To 4
With Reg1
'.IgnoreCase = True
Select Case i 'each Case = one specific string parsed
Case 1
'pull everything after Caller (separated by :), and stop at line end \n
.Pattern = "(Caller[:]([\w-\s]*)\s*)\n"
Case 2
.Pattern = "(Phone[:]([\d-\s]*)\s*)\n"
'#### CASE 3 NOT WORKING
Case 3
'pull everything after For (separated by :), and stop at the dash [-]
.Pattern = "(For[:]([\w-\s]*)\s*)[-]"
Case 4
'pull everything after MSGID, and stop at the dash [-]
.Pattern = "(MSGID[:]([\w-\s]*)\s*)[-]"
End Select
End With
If Reg1.Test(sText) Then
' each "(\w*)" and the "(\s)" 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))
Next
xlSheet.Range("a" & rCount) = .ReceivedTime
xlSheet.Range("b" & rCount) = vText
xlSheet.Range("c" & rCount) = vText2
xlSheet.Range("d" & rCount) = vText3
xlSheet.Range("e" & rCount) = vText4
'xlSheet.Range("D" & rCount) = .Subject
'xlSheet.Range("f" & rCount) = vText5
'##Checking on output per iteration:
'MsgBox ("inputting data in row #" & rCount)
' next line
rCount = rCount + 1
End If
Next i
' do whatever
Debug.Print .Subject
End With
Next
'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
Set objItems = Nothing
Set objFolder = Nothing
Set objOL = Nothing
End Sub
I'd move the regex into a separate function:
Function ExtractText(txt As String, patt As String)
Static reg As Object
Dim matches, rv As String 'EDIT: moved from Static line
If reg Is Nothing Then
Set reg = CreateObject("VBScript.RegExp")
'set up IgnoreCase etc here...
End If
reg.Pattern = patt
If reg.Test(txt) Then
Set matches = reg.Execute(txt)
rv = matches(0).submatches(1)
End If
ExtractText = rv
End Function
Then the core of your main code becomes something like this:
Set objOL = Outlook.Application
Set OutlookNamespace = objOL.GetNamespace("MAPI")
Set objFolder = OutlookNamespace.GetDefaultFolder(olFolderInbox).Folders("SubFolder").Folders("SubSubFolder")
Set objItems = objFolder.Items
For Each olItem In objItems
sText = olItem.Body
xlSheet.Range("a" & rCount) = .ReceivedTime
xlSheet.Range("b" & rCount) = ExtractText(sText, "(Caller[:]([\w-\s]*)\s*)\n")
xlSheet.Range("c" & rCount) = ExtractText(sText, "(Phone[:]([\d-\s]*)\s*)\n")
xlSheet.Range("d" & rCount) = ExtractText(sText, "(For[:]([\w-\s]*)\s*)[-]")
xlSheet.Range("e" & rCount) = ExtractText(sText, "(MSGID:\s?(\d{1,})-)")'<<edit
'xlSheet.Range("D" & rCount) = .Subject
'xlSheet.Range("f" & rCount) = vText5
'MsgBox ("inputting data in row #" & rCount)
rCount = rCount + 1
Next olItem

Referencing Excel sheet generates error: Variable not set

I am trying to extract 2 fields from the following email.
How would you like your name to appear on the CERTIFICATE OF PARTICIPATION?
Joe Johnson (sample name)
Email Address Required Joe.Johnson#xxxmail.com
and the email address after "Required" which is Joe.Johnson#xxxmail.com
I want to import those two fields to Excel so I can populate a certificate and return it to the email address. Ultimately I would like to have code that would do all of the above but for the time being I would be happy just to get the following code to work.
I get a run time error on the following: Set xlSheet = xlWB.Sheets("Sheet1")
Sub ExtractEmailData()
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Dim olItem As Object
Dim vText As Variant
Dim sText As String
Dim vItem As Variant
Dim i As Long
Dim rCount As Long
Dim bXStarted As Boolean
Const strPath As String = "D:\Joe\Documents\2018 TEAMS Certificate.xlsm" 'the path of the workbook
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("Sheet1")
'Process each selected record
rCount = xlSheet.UsedRange.Rows.Count
For Each olItem In Application.ActiveExplorer.Selection
sText = olItem.Body
vText = Split(sText, Chr(13))
'Find the next empty line of the worksheet
rCount = rCount + 1
'Check each line of text in the message body
For i = UBound(vText) To 0 Step -1
If InStr(1, vText(i), "PARTICIPATION?") > 0 Then
vItem = Split(vText(i), Chr(60))
vItem = Split(vItem(1), Chr(62))
xlSheet.Range("A" & rCount) = Trim(vItem(1))
End If
If InStr(1, vText(i), "Email Address Required") > 0 Then
vItem = Split(vText(i), Chr(58))
xlSheet.Range("B" & rCount) = Trim(vItem(1))
End If
Next i
xlWB.Save
Next olItem
xlWB.Close SaveChanges:=True
If bXStarted Then
xlApp.Quit
End If
Set xlApp = Nothing
Set xlWB = Nothing
Set xlSheet = Nothing
Set olItem = Nothing
End Sub
I am new to VBA.
Just to offer a simple fix, in case the problem is simple. Does "D:\Joe\Documents\2018 TEAMS Certificate.xlsm" definitely have a worksheet named "Sheet1"? If not, maybe you meant:
Set xlSheet = xlWB.Sheets(1)

Checking for the presence of an attachment in outlook and display the data

The code below is used to extract data of email from any folder in Outlook and display those data in an Excel file.
The data will display the sender name,sender email address, the subject and the time received.
But is there a way for the code to detect if the email have any attachment and will display yes or no for the presence of attachment or attachments in the email in another Excel column ?
Attached below is the code:
Option Explicit
Sub ExportDataToExcel()
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 olItem As Outlook.MailItem
Dim obj As Object
Dim strColA, strColB, strColC, strColD As String
Dim currentExplorer As Outlook.NameSpace
Dim Selection As Outlook.MAPIFolder
' Get Excel set up
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 a specific workbook to input the data ============
'the path of the workbook under the windows user account
enviro = CStr(Environ("USERPROFILE"))
strPath = enviro & "\Desktop\New folder\OutlookItems.xlsx"
Set xlWB = xlApp.Workbooks.Open(strPath)
Set xlSheet = xlWB.Sheets("Sheet1")
'================== End Specific workbook ====================
'=================== Use New Workbook ========================
'Set xlWB = xlApp.Workbooks.Add
'Set xlSheet = xlWB.Sheets("Sheet1")
'================== end use new workbook =====================
' Add column names
xlSheet.Range("A1") = "SENDER"
xlSheet.Range("B1") = "SENDER ADDRESS"
xlSheet.Range("C1") = "MESSAGE SUBJECT"
xlSheet.Range("D1") = "RECEIVED TIME"
xlSheet.Range("A1").Interior.Color = RGB(0, 255, 255)
xlSheet.Range("B1").Interior.Color = RGB(0, 255, 255)
xlSheet.Range("C1").Interior.Color = RGB(0, 255, 255)
xlSheet.Range("D1").Interior.Color = RGB(0, 255, 255)
' Process the message record
On Error Resume Next
'Find the next empty line of the worksheet
rCount = xlSheet.Range("A" & xlSheet.Rows.Count).End(-4162).Row
'needed for Exchange 2016. Remove if causing blank lines.
rCount = rCount + 1
' get the values from outlook
Set currentExplorer = Application.GetNamespace("MAPI")
Set Selection = currentExplorer.PickFolder
For Each obj In Selection.Items
Set olItem = obj
'collect the fields
strColA = olItem.SenderName
strColB = olItem.SenderEmailAddress
strColC = olItem.Subject
strColD = olItem.ReceivedTime
'================== Get all recipient addresses ===================
' instead of To names
Dim strRecipients As String
Dim Recipient As Outlook.Recipient
For Each Recipient In olItem.Recipients
strRecipients = Recipient.Address & "; " & strRecipients
Next Recipient
'================== end all recipients addresses ==================
'==================== Get the Exchange address ====================
' if not using Exchange, this block can be removed
Dim olEU As Outlook.ExchangeUser
Dim oEDL As Outlook.ExchangeDistributionList
Dim recip As Outlook.Recipient
Set recip = Application.Session.CreateRecipient(strColB)
If InStr(1, strColB, "/") > 0 Then
' if exchange, get smtp address
Select Case recip.AddressEntry.AddressEntryUserType
Case OlAddressEntryUserType.olExchangeUserAddressEntry
Set olEU = recip.AddressEntry.GetExchangeUser
If Not (olEU Is Nothing) Then
strColB = olEU.PrimarySmtpAddress
End If
Case OlAddressEntryUserType.olOutlookContactAddressEntry
Set olEU = recip.AddressEntry.GetExchangeUser
If Not (olEU Is Nothing) Then
strColB = olEU.PrimarySmtpAddress
End If
Case OlAddressEntryUserType.olExchangeDistributionListAddressEntry
Set oEDL = recip.AddressEntry.GetExchangeDistributionList
If Not (oEDL Is Nothing) Then
strColB = olEU.PrimarySmtpAddress
End If
End Select
End If
' ==================== End Exchange section =====================
'write them in the excel sheet
xlSheet.Range("A" & rCount) = strColA ' sender name
xlSheet.Range("B" & rCount) = strColB ' sender address
xlSheet.Range("C" & rCount) = strColC ' message subject
xlSheet.Range("D" & rCount) = strColD ' recieved time
'Next row
rCount = rCount + 1
' size the cells
xlSheet.Columns("A:D").EntireColumn.AutoFit
xlSheet.Columns("C:C").ColumnWidth = 100
xlSheet.Range("A2").Select
xlSheet.Columns("A:D").VerticalAlignment = xlTop
Next
xlApp.Visible = True
' to save but not close
'xlWB.Save
' to save and close
' xlWB.Close 1
' If bXStarted Then
' xlApp.Quit
' End If
' end save and close
Set olItem = Nothing
Set obj = Nothing
Set currentExplorer = Nothing
Set xlSheet = Nothing
Set xlWB = Nothing
Set xlApp = Nothing
End Sub
Sure, check that olItem.Attachments.Count > 0
Simply use If olItem.Attachments.Count > 0 Then strColE = "YES"
Example
'================== end all recipients addresses ==================
' check for attachment
Dim strColE As String
If olItem.Attachments.Count > 0 Then strColE = "YES"
'==================== Get the Exchange address ====================
Then add xlSheet.Range("E" & rCount) = strColE ' Attament to
'write them in the excel sheet
xlSheet.Range("A" & rCount) = strColA ' sender name
xlSheet.Range("B" & rCount) = strColB ' sender address
xlSheet.Range("C" & rCount) = strColC ' message subject
xlSheet.Range("D" & rCount) = strColD ' recieved time
xlSheet.Range("E" & rCount) = strColE ' Attament

Need Outlook Attachments File Names ( or only extensions ) counts exported for selected emails into Excel

I wish to extract the filenames of the attachments I have received into the public folder and extract ( paste ) them into the excel file for easy analysis.
I have the below code however it is only selecting details of 1 email.
I wish to understand where it does wrong.
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 myAttachments As Outlook.Attachments
Dim j As Long
Dim i As Integer
Dim Report As String
Dim attachment As attachment
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 & "\Documents\test.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(strPath)
Set xlSheet = xlWB.Sheets("Sheet1")
' 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
Set myAttachments = olItem.Attachments
'collect the fields
Next
For Each Selection In Selection
If Selection.Class = olMail Then
End If
For Each attachment In olItem.Attachments
Report = strColC & GetAttachmentInfo(attachment)
strColB = olItem.Attachments.Count
strColD = olItem.SenderEmailAddress
strColE = olItem.Categories
strColF = olItem.ReceivedTime
'write them in the excel sheet
xlSheet.Range("B" & rCount) = strColB
xlSheet.Range("c" & rCount) = Report
xlSheet.Range("d" & rCount) = strColD
xlSheet.Range("e" & rCount) = strColE
xlSheet.Range("f" & rCount) = strColF
'Next row
rCount = rCount + 1
Next
Next
xlWB.Close 1
If bXStarted Then
xlApp.Quit
End If
Set olItem = Nothing
Set obj = Nothing
Set currentExplorer = Nothing
Set xlApp = Nothing
Set xlWB = Nothing
Set xlSheet = Nothing
End Sub
Public Function GetAttachmentInfo(attachment As attachment)
On Error GoTo On_Error
Dim Report
Dim strColA, strColB, strColC, strColD, strColE, strColF As String
GetAttachmentInfo = ""
Report = strColA & "Display Name: " & attachment.DisplayName
Report = strColC & "File Name: " & attachment.filename
GetAttachmentInfo = Report
Exiting:
Exit Function
On_Error:
MsgBox "error=" & Err.Number & " " & Err.Description
Resume Exiting
End Function
I do not have access to Outlook at the moment so the following is from studying the macro rather than trying to run it.
Public Function GetAttachmentInfo(attachment As attachment)
You need As String at the end if you want a value returned. You are using attachment both as a keyword and as the name of a parameter. Please rename the parameter.
Report = strColA & "Display Name: " & attachment.DisplayName
Report = strColC & "File Name: " & attachment.filename
strColA and strColA have be declared with a Dim statement but have not been given values so are blank. The second statement overwrites the value of Report set by the first.
I see examples of your use of On Error repeatedly. I did the same until I realised it was totally unhelpful. During development, you want the interpreter to stop on the statement giving the error so you know what to correct. In a production macro, released to non-technical users, you need something more friendly. I suggest you delete this code.
I cannot see why you are getting the name of the first attachment but not the other attachments. I suggest you correct these errors and then repost your revised code.

Copy data in a structured text block from Outlook message to Excel sheet

An integer number follows "Purchase Order:" in the email body.
All emails follow this format. http://i.stack.imgur.com/1Ck9Q.jpg
The number is to be pasted into the next empty row of the Excel spreadsheet.
I have a spreadsheet on my desktop named "test" to try this with.
I've tried about 4 or 5 different VBA codes I found using Google with no luck.
A method to address this frequently asked question is shown here. http://social.msdn.microsoft.com/Forums/en-US/f1ab97d9-8fef-46cc-bbe0-e597370ed1c2/export-content-from-outlook-2010-emails-to-excel-spreadsheet?forum=isvvba
The code goes into Outlook not Excel.
Option Explicit
Sub CopyToExcel()
Dim xlApp As Object
Dim xlWB As Object
Dim xlSheet As Object
Dim olItem As Outlook.MailItem
Dim vText As Variant
Dim sText As String
Dim vItem As Variant
Dim i As Long
Dim rCount As Long
Dim bXStarted As Boolean
Const strPath As String = " C:\path\desktop\test.xlsx" 'the path of the workbook
If Application.ActiveExplorer.Selection.Count = 0 Then
MsgBox "No Items selected!", vbCritical, "Error"
Exit Sub
End If
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("Sheet1")
'Process each selected record
For Each olItem In Application.ActiveExplorer.Selection
sText = olItem.Body
vText = Split(sText, Chr(13))
'Find the next empty line of the worksheet
rCount = xlSheet.UsedRange.Rows.Count
'Check each line of text in the message body
For i = UBound(vText) To 0 Step -1
rCount = rCount + 1
If InStr(1, vText(i), "Purchase order:") > 0 Then
vItem = Split(vText(i), Chr(58))
xlSheet.Range("A" & rCount) = Trim(vItem(1))
End If
' Where more data is to be extracted add more of these lines.
'If InStr(1, vText(i), "Second label:") > 0 Then
' vItem = Split(vText(i), Chr(58))
' xlSheet.Range("B" & rCount) = Trim(vItem(1))
'End If
'If InStr(1, vText(i), "Third label:") > 0 Then
' vItem = Split(vText(i), Chr(58))
' xlSheet.Range("C" & rCount) = Trim(vItem(1))
'End If
Next i
xlWB.Save
Next olItem
xlWB.Close SaveChanges:=True
If bXStarted Then
xlApp.Quit
End If
Set xlApp = Nothing
Set xlWB = Nothing
Set xlSheet = Nothing
Set olItem = Nothing
End Sub

Resources