• Outlook User
  • Exchange Admin
  • Office 365
  • Outlook Developer
  • Outlook.com
  • Outlook Mac
  • Outlook & iCloud
    • Common Problems
    • Outlook BCM
    • Utilities & Addins
    • Video Tutorials
    • EMO Archives
    • Outlook Updates
    • Outlook Apps
    • Forums

Parsing text fields in Outlook

Slipstick Systems

› Developer › Parsing text fields in Outlook

Last reviewed on December 30, 2013     15 Comments

September 15, 2012 by Diane Poremsky 15 Comments

An Outlook user wanted to know how to get part of a field and insert it into the message body. This is actually easy to do.

How do I get the domain name from an email address and add it to the message body? I have an email list of clients in Outlook and I would like to send them email. In the body part of mail, I would like to add their website domain. For example, I need to send mail to bob@domain.com and want to insert "Reference: domain.com".

You just need to find the position where the delimiting characters (in this case, the @ sign) is and get the letters going forward or backward.

The good news: It's less complicated than it sounds. Once you get that, you can insert it into a message body using Item.Body = "Reference: " & string . See Send message to contact for an example.

You can also use RegEx to find strings. See Use RegEx to parse message text

You can use this for more than just parsing an email address. If you receive email containing clearly identified fields ("Email: me@domain.com First Name: Mary Last Name: Smith") you can use this method to save the data.

To do this you need to use the VBA functions Len, Right, Left, Mid, and InStr.

Len

Len gets the length of a string, beginning at a starting point.

If you use test = Len("diane"), test will return 5.

Left or Right

Left or right will get the left-most or right-most characters.

string = Left ("phrase", get this many characters)
string = right ("phrase", get this many characters)

In test = Left ("diane", 3), test will equal "dia", the first 3 letters. Right("diane", 3) would give us "ane".

Mid

Mid gets words from the middle of a phrase. You need to enter both the starting point and how many characters.

string = Mid("phrase", start at, get this many characters)

If we use test = Mid("diane", 2, 3), it starts at the second characters and gets the next 3, for "ian".

InStr

InStr gets the position of a character within a string.

integer = InStr(start at, "phrase", "character or string")

So, test = InStr(1, "diane", "i") tells us the position of the i in diane is 2. The 1 tells it to start at the beginning of the string or phrase.

If we know the character we want is in the string twice, we can tell it to start looking later:
test = InStr(4, "slipstick", "i") tells me that there is an i in position 7.

We can look for the starting position of multi-character strings too: test = InStr(1, "slipstick", "ic") returns a 7.

To use InStr in a macro, such as to look for one category when multiple categories are assigned to an item, you'd use this format:

If InStr(Item.Categories, "my category") Then

Match upper or lower case

You can ignore upper letters in a string by using the LCASE function: LCASE(String)

LCase(Item.Body) converts the message body to all lower case. This allows the code to work even if someone uses mixed case or all caps.

For example, this sample looks for the word "something" as the first word in the message body. Because it uses LCASE, it will match Something, something, SOmething, or SOMETHING.

If Left(LCase(Item.Body), 9) = "something" Then
'do something
End If

Combine the functions

By putting these functions together we can split Outlook fields apart, trim the length of fields, or look for specific characters in a field.

Below are some very basic examples of how to use these functions. Generally speaking, you want to get each variable separately to use in the Left, Right, or Mid functions as it makes it easier to read and find mistakes.

For example, this line works, but is harder to read and understand. This code gets the right most characters of the selected contacts email address, up to the position of the @ sign (i.e., the domain name):

strDomain = Right(oContact.Email1Address, Len(oContact.Email1Address) - InStr(1, oContact.Email1Address, "@"))

This code does the same as the version above but is easier to follow.

Get position of the @ sign

intATsign = InStr(1, oContact.Email1Address, "@")

Get the length of the address, minus the position of the @ sign

intAddress = Len(oContact.Email1Address) - intATsign

Get the right most characters from the phrase

strDomain = Right(oContact.Email1Address, intAddress)

This code shows how to use the Mid function to start counting from the position of a character and get the next xx characters.

intATsign = InStr(1, oContact.Email1Address, "@")
intAddress = Len(oContact.Email1Address) - intATsign
strDomain = Mid(oContact.Email1Address, intATsign + 1, intAddress)

Trim

Although not one of the functions you'll use to find and parse data, the Trim function can be useful to remove non-printing and leading or ending spaces from text.

string = Trim(string)

More Information

Extract data from a structured text block Outlookcode.com example that extracts the data from any label-data pair that appears in a block of text, where all the label-data pairs are on separate lines. For example, get the data from an email message sent using a web form, where the message has multiple lines each with a different Label: Data pair.

The following pages contain macros that use these functions.
Print Outlook email attachments as they arrive
Add a Category to Contacts in a Contact Group (DL)
Saving All Messages to the Hard Drive Using VBA
Check for missing attachments before sending an Outlook email message
Adding Birthdays and Anniversaries to Outlook's Calendar
Removing Birthdays and Anniversaries from the Calendar
Disable Outlook 2010's No Subject Warning using VBA
Find the Distribution Lists a Contact Belongs to
Remove Cancelled Meeting Requests from Resource Calendar
Assign a keyword to a message field for tracking

Parsing text fields in Outlook was last modified: December 30th, 2013 by Diane Poremsky

Related Posts:

  • Merge to email using only Outlook
  • Create a deferred Birthday message for an Outlook Contact
  • Use Instant search to find messages from a contact
  • Mail merge and Send from a Distribution Group

About Diane Poremsky

A Microsoft Outlook Most Valuable Professional (MVP) since 1999, Diane is the author of several books, including Outlook 2013 Absolute Beginners Book. She also created video training CDs and online training classes for Microsoft Outlook. You can find her helping people online in Outlook Forums as well as in the Microsoft Answers and TechNet forums.

15
Leave a Reply

2500
Photo and Image Files
 
 
 
Audio and Video Files
 
 
 
Other File Types
 
 
 
2500
Photo and Image Files
 
 
 
Audio and Video Files
 
 
 
Other File Types
 
 
 

  Subscribe  
newest oldest most voted
Notify of
BenM
BenM

Hi Diane, Can you help me with similar case? I'm receiving multiple email from automated server with the same subject, but the email body contain a different item#. I need a script to run (I'll set a rule to run the script for new emails from the specific sender) that will find the item# (digits) within the email body, edit the subject and change it to item# and save. here is an example : 1. Email received: From: example@domain.com Subject: New email This item# is for you. bla bla bla. 2. Run rule: a. from : example@domain.com & Subject: New email b. Run script : i. find : item# ii. Set email subject to: item# iii. Save email. 3. Result: From: Example@domain.com Subject: item# This item# is for you. bla bla bla.

Vote Up00Vote Down Reply
September 8, 2016 4:15 pm
Diane Poremsky
Diane Poremsky

You'll want to use regex to get the values from the body.

Use RegEx to extract text from an Outlook email message

Vote Up00Vote Down Reply
February 6, 2017 12:36 am
Brent Schneider
Brent Schneider

myReply.HTMLBody = " Hello" & Mid$(Item.SenderName, InStr(1, Item.SenderName, " ")) & ", " & vbCrLf & myReply.HTMLBody

Hello,

The above line of code has been assisting me return the name of an email recipient to an email body. The problem I am having is this current line of code returns the First Name "Space" Middle Initial.

From the email name format Schneider, Brent T I am getting Brent T

I would like to only receive the first name so it reads as Hello Brent, instead of Hello Brent T, in the email body.

I believe with addition combination of the functions Mid$, Right$, Len, InStr, InStrRev in the line I would be able to get what I want but I am at a loss.

Any assistance would be greatly appreciated,
Brent Schneider

Vote Up00Vote Down Reply
September 7, 2016 10:53 am
Diane Poremsky
Diane Poremsky

i would get the brent t into a variable, then split it at the space, using either instr as you are now or using the split function. Or you could try using instrrev to split the full name at the last space - but if you only want the first name, you'll still need to process it twice (i think).

Vote Up00Vote Down Reply
September 8, 2016 1:28 am
Arumugam
Arumugam

How do I get the e-mail ID, contact number from an message body and add it to the to address? we receive the client mail ID through mail body form the search engine companies. I would like to send the client an automatic email using templates. In the body part of mail, I would like to extract the product they are seeking and I will insert it in to the subject field. For example, I need get the mail ID as bob@domain.com I want to copy this and use in to address. I want to copy the product "wireless" and put it in the subject. Please help

Vote Up00Vote Down Reply
February 18, 2016 3:03 pm
Diane Poremsky
Diane Poremsky

Use regex to grab the address and assign it to a variable then you can assign it to the To field. See https://www.slipstick.com/developer/regex-parse-message-text/ for samples.

Vote Up00Vote Down Reply
February 23, 2016 1:21 am
Brent
Brent

Here is the code: Sub Country() Dim olApp As Outlook.Application Dim olNS As Outlook.NameSpace Dim olFolder As Outlook.MAPIFolder Dim Item As MailItem Dim regEx As Object Dim olMatches As Object Dim strBody As String Dim bcount As String Dim badAddresses As Variant Dim i As Long Dim xlApp As Object 'Excel.Application Dim xlwkbk As Object 'Excel.Workbook Dim xlwksht As Object 'Excel.Worksheet Dim xlRng As Object 'Excel.Range Set olApp = Outlook.Application Set olNS = olApp.GetNamespace("MAPI") Set olFolder = olNS.Folders("mail.com").Folders("Inbox").Folders("New Emails") Set regEx = CreateObject("VBScript.RegExp") 'define regular expression regEx.Pattern = "(Reply to What Country are you from\?:\s*([A-Za-z ]*\r))" regEx.IgnoreCase = True regEx.MultiLine = True ' set up size of variant bcount = olFolder.Items.count ReDim badAddresses(1 To bcount) As String ' initialize variant position counter i = 0 ' parse each message in the folder holding the bounced emails For Each Item In olFolder.Items i = i + 1 strBody = olFolder.Items(i).Body Set olMatches = regEx.Execute(strBody) If olMatches.count >= 1 Then badAddresses(i) = olMatches(0) Item.UnRead = False End If Next Item ' write everything to Excel Set xlApp = GetExcelApp If xlApp Is Nothing Then GoTo ExitProc If Not IsFileOpen("\Desktop\email.xlsx") Then Set xlwkbk = xlApp.Workbooks.Open(Environ("USERPROFILE") & "\Desktop\email.xlsx") End If Set xlwksht = xlwkbk.Sheets(1)… Read more »

Vote Up00Vote Down Reply
August 27, 2015 12:46 pm
Brent
Brent

Diane,
Thanks, but I tried both of your recommendations and I get a run time error when I changed olmatches(1). Also, I tried to wrap the pattern as well and it still comes back with "What Country are you from\?: India". Not sure why it still pulls the preceding text before the match code.

Vote Up00Vote Down Reply
August 27, 2015 9:26 am
Diane Poremsky
Diane Poremsky

Can you post the full code you are using to get India? The number inside the match() counts the number of parentheses - starting with 0 (for one pair) so match(0) should get just India when the only parens around the regex for India. If it's match(1), and you use () around the entire pattern then should get the second set, which is around the regex for India.

Vote Up00Vote Down Reply
August 27, 2015 12:26 pm
Brent
Brent

Thanks! I had to change up a little to get it to work, but this code below works now:
"Reply to What Country are you from\?:\s*([A-Za-z ]*\r)"
Is there a way to only retrieve everything after Reply to What Country are you from\?:
This code pulls Reply to What Country are you from\?: India. This works, but I have to cleanup in Excel, so just curious as to how I could retrieve only "India".

I appreciate your help!!!

Vote Up00Vote Down Reply
August 27, 2015 12:17 am
Diane Poremsky
Diane Poremsky

With that pattern, it should only get what is in the () in the match code: olmatches(0). Try olmatches(1) and wrap the pattern in (): "(Reply to What Country are you from\?:\s*([A-Za-z ]*\r))".

Vote Up00Vote Down Reply
August 27, 2015 12:26 am
Brent
Brent

Diane, I am trying to alter a piece of code that is successfully extracting email addressed from incoming outlook emails and places them in an Excel file. However, I wanted to try and extract the country they are coming from as well from those emails and place in excel column B1. The fact that country is on the row beneath where I am trying to reference may be causing problems. ---------------------------------------------- Here is a sample form reply where I am want to extract both email and country. A survey on your site named Web Pages Load Times has been completed Reply to Valid Email Address: example@gmail.com Reply to What Country are you from?: India ---------------------------------------------- Here is the code that I am using and is successfully pulling emails and placing them in an excel document: Option Explicit Sub badAddress() Dim olApp As Outlook.Application Dim olNS As Outlook.NameSpace Dim olFolder As Outlook.MAPIFolder Dim Item As MailItem Dim regEx As Object Dim olMatches As Object Dim strBody As String Dim bcount As String Dim badAddresses As Variant Dim i As Long Dim xlApp As Object 'Excel.Application Dim xlwkbk As Object 'Excel.Workbook Dim xlwksht As Object 'Excel.Worksheet Dim xlRng As Object 'Excel.Range Set… Read more »

Vote Up10Vote Down Reply
August 25, 2015 5:13 pm
Diane Poremsky
Diane Poremsky

You need to use case statements or a function to handle two different patterns. See https://www.slipstick.com/developer/regex-parse-message-text/ for an example.

regEx.Pattern = "Reply to What Country are you from?:\s\n([A-Za-z ]*)"
I *think* \n is linefeed - or it might be \r.

Vote Up0-1Vote Down Reply
August 26, 2015 9:35 pm
Peter
Peter

Hello Diane,
From the Netherlands, I write you to have a solution for my problem.
I have in a word-document a text like

I live in Amsterdam (capital of the Netherlands) since I was young.

and I want to select with the help of a Word Macro to select the part

(capital of the Netherlands)

which isn't difficult thanks to commands like you taught me with instr()

but HOW can I get it into my clipboard?

Selection.Copy
pdwnew = Selection

a = InStr(pdwnew, "(")
MsgBox (a)
pdwnew = Mid(pdwnew, a, Len(pdwnew) - a)
MsgBox (pdwnew)

b = InStr(pdwnew, ")")
MsgBox (b)
pdwnew = Mid(pdwnew, 1, b)
MsgBox (pdwnew)

' what must I do to put it into my clipboard?

Thank you very much to solve the problem for me... I tried to solve the problem and spend many hours already.
Peter

Vote Up3-3Vote Down Reply
June 25, 2014 3:40 am
Diane Poremsky

See the macro at the end of this article: https://www.slipstick.com/developer/code-samples/paste-clipboard-contents-vba/ - it shows how to copy contents to the clipboard. If you are going to use the value within Outlook or Word, you can save it in a string and return the string when needed.

Vote Up1-3Vote Down Reply
June 25, 2014 11:56 pm

Visit Slipstick Forums.
What's New at Slipstick.com

Latest EMO: Vol. 24 Issue 3

Support Services

Do you need help setting up Outlook, moving your email to a new computer, migrating or configuring Office 365, or just need some one-on-one assistance?

Subscribe to Exchange Messaging Outlook






Our Sponsors

  • Popular
  • Latest
  • Week Month All
  • Adjusting Outlook's Zoom Setting in Email
  • The Signature or Stationery and Fonts button doesn't work
  • Security Certificate Warning in Microsoft Outlook
  • This operation has been cancelled due to restrictions
  • How to Remove the Primary Account from Outlook
  • Two Copies of Sent Messages in Outlook
  • iCloud error: Outlook isn't configured to have a default profile
  • Outlook's Rules and Alerts: Run a Script
  • Outlook is Not Recognized as the Default Email Client
  • To Cc or Bcc a Meeting Request
  • Outlook.com: Manage Subscriptions
  • Group By Views don’t work in To-Do List
  • Category shortcuts don’t work
  • How to disable the Group By view in Outlook
  • Adjusting Outlook's Zoom Setting in Email
  • Change the Subject of an Incoming Message
  • Creating Signatures in Outlook
  • Scheduling a Recurring Message
  • OneNote is missing from Office 365 / 2019
  • Create Rules using PowerShell
Ajax spinner

Newest VBA Samples

Adjusting Outlook's Zoom Setting in Email

Move email items based on a list of email addresses

Remove prefix from Gmail meeting invitations

How to hide LinkedIn, Facebook, Google and other extra contact folders in Outlook.com

Use VBA to create a Mail Merge from Excel

Open multiple Outlook windows when Outlook starts

Set most frequently used Appointment Time Zones

How to change the From field on incoming messages

VBA: File messages by client code

Update Contact Area Codes

Recent Bugs List

Microsoft keeps a running list of issues affecting recently released updates at Fixes or workarounds for recent issues in Outlook for Windows.

Windows 10 Issues

  • iCloud, Outlook 2016, and Windows 10
  • Better Outlook Reminders?
  • Coming Soon to Windows 10: Office 365 Search
  • Outlook Links Won’t Open In Windows 10
  • BCM Errors after Upgrading to Windows 10
  • Outlook can’t send mail in Windows 10: error Ox800CCC13
  • Missing Outlook data files after upgrading Windows?

Outlook 2016 Top Issues

  • The Windows Store Outlook App
  • Emails are not shown in the People Pane (Fixed)
  • Calendars aren’t printing in color
  • The Signature or Stationery and Fonts button doesn’t work
  • Outlook’s New Account Setup Wizard
  • BCM Errors after October 2017 Outlook Update
  • Excel Files Won’t Display in Reading Pane
  • Outlook 2016: No BCM
  • Exchange Account Set-up Missing in Outlook 2016

VBA Basics

How to use the VBA Editor

Work with open item or selected item

Working with All Items in a Folder or Selected Items

VBA and non-default Outlook Folders

Backup and save your Outlook VBA macros

Get text using Left, Right, Mid, Len, InStr

Using Arrays in Outlook macros

Use RegEx to extract message text

Paste clipboard contents

Windows Folder Picker

Custom Forms

Designing Microsoft Outlook Forms

Set a custom form as default

Developer Resources

Developer Resources

Developer Tools

Outlook-tips.net Samples

VBOffice.net samples

OutlookCode.com

SlovakTech.com

Outlook MVP David Lee

MSDN Outlook Dev Forum

Repair PST

Convert an OST to PST

Repair damaged PST file

Repair large PST File

Remove password from PST

Merge Two Data Files

Sync & Share Outlook Data

  • Share Calendar & Contacts
  • Synchronize two computers
  • Sync Calendar and Contacts Using Outlook.com
  • Sync Outlook & Android Devices
  • Sync Google Calendar with Outlook
  • Access Folders in Other Users Mailboxes
  • “Live” Group Calendar Tools

Convert to / from Outlook

  • Converting Messages and Calendar or
    Address books
  • Moving Outlook to a New Computer
  • Moving Outlook 2010 to a new Windows computer
  • Moving from Outlook Express to Outlook

Recover Deleted Items

  • Recover deleted messages from .pst files
  • Are Deleted Items gone forever in Outlook?

Outlook 2013 Absolute Beginner's Guide

Diane Poremsky [Outlook MVP]

Make a donation

Calendar Tools

Schedule Management

Calendar Printing Tools

Calendar Reminder Tools

Calendar Dates & Data

Time and Billing Tools

Meeting Productivity Tools

Duplicate Remover Tools

Mail Tools

Sending and Retrieval Tools

Mass Mail Tools

Compose Tools

Duplicate Remover Tools

Mail Tools for Outlook

Online Services

Productivity

Productivity Tools

Automatic Message Processing Tools

Special Function Automatic Processing Tools

Housekeeping and Message Management

Task Tools

Project and Business Management Tools

Choosing the Folder to Save a Sent Message In

Run Rules on messages after reading

Help & Suggestions

Outlook Suggestion Box (UserVoice)

Slipstick Support Services

Contact Tools

Data Entry and Updating

Duplicate Checkers

Phone Number Updates

Contact Management Tools

Sync & Share

Share Calendar & Contacts

Synchronize two machines

Sharing Calendar and Contacts over the Internet

More Tools and Utilities for Sharing Outlook Data

Access Folders in Other Users Mailboxes

View Shared Subfolders in an Exchange Mailbox

"Live" Group Calendar Tools

Home | Outlook User | Exchange Administrator | Office 365 | Outlook.com | Outlook Developer
Outlook for Mac | Outlook BCM | Common Problems | Utilities & Addins | Tutorials
Outlook & iCloud Issues | Outlook Apps
EMO Archives | About Slipstick | Advertise | Slipstick Forums
Submit New or Updated Outlook and Exchange Server Utilities

Send comments using our Feedback page
Copyright © 2019 Slipstick Systems. All rights reserved.
Slipstick Systems is not affiliated with Microsoft Corporation.

You are going to send email to

Move Comment