• Outlook User
  • New Outlook app
  • Outlook.com
  • Outlook Mac
  • Outlook & iCloud
  • Developer
  • Microsoft 365 Admin
    • Common Problems
    • Microsoft 365
    • Outlook BCM
    • Utilities & Addins

Parsing text fields in Outlook

Slipstick Systems

› Developer › Parsing text fields in Outlook

Last reviewed on May 19, 2022     22 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

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: May 19th, 2022 by Diane Poremsky

Related Posts:

  • Merge to email using only Outlook
  • Assign an Email Account to an Outlook Contact
  • Use RegEx to extract text from an Outlook email message
  • 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.

Subscribe
Notify of
22 Comments
newest
oldest most voted
Inline Feedbacks
View all comments

Iñigo (@guest_218489)
July 1, 2021 7:13 am
#218489

Hi Diane, is there a wildcard option for the InStr formula? I'd like to find a string that starts with a "D", then some character, then a "-", so both strings like "DB-" and "D4-" get found.
Many thanks!
Ingo

0
0
Reply
Diane Poremsky(@diane-poremsky)
Author
Reply to  Iñigo
July 1, 2021 8:20 am
#218490

No, instr does not use wildcards - but regex will work.

One of my regex examples is here - Use RegEx to extract text from an Outlook email message (slipstick.com)

0
0
Reply
Daniel White (@guest_217999)
April 23, 2021 11:41 am
#217999

Diane, I am looking to build an email forward event from words in an email. can you help with this, what would you charge?

0
0
Reply
Diane Poremsky(@diane-poremsky)
Author
Reply to  Daniel White
April 23, 2021 12:11 pm
#218000

It depends on exactly what you want to do and if I have a macro published that works as a base with only customizations needed. Generally, $100 - 200 to tweak an existing macro, but could be lower if the tweaks are simple. (And higher if I need to work from scratch.)

Last edited 4 years ago by Diane Poremsky
0
0
Reply
Daniel White (@guest_218002)
Reply to  Diane Poremsky
April 23, 2021 12:32 pm
#218002

So basically I want to take an email that in the body of the email it says CompanyName: @companyname.com I want to grab, then have it forward the email to the BACK@companyname.com

0
0
Reply
Diane Poremsky(@diane-poremsky)
Author
Reply to  Daniel White
April 23, 2021 11:37 pm
#218009

That is basically this - Run a script rule: Autoreply using a template (slipstick.com)

0
0
Reply
Diane Poremsky(@diane-poremsky)
Author
Reply to  Daniel White
April 23, 2021 11:38 pm
#218010

or this one
Run a Script Rule: Forwarding Messages (slipstick.com)

0
0
Reply
BenM (@guest_201442)
September 8, 2016 4:15 pm
#201442

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.

0
0
Reply
Diane Poremsky(@diane-poremsky)
Author
Reply to  BenM
February 6, 2017 12:36 am
#204333

You'll want to use regex to get the values from the body.
https://www.slipstick.com/developer/regex-parse-message-text/

0
0
Reply
Brent Schneider (@guest_201395)
September 7, 2016 10:53 am
#201395

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

0
0
Reply
Diane Poremsky(@diane-poremsky)
Author
Reply to  Brent Schneider
September 8, 2016 1:28 am
#201412

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).

0
0
Reply
Arumugam (@guest_196591)
February 18, 2016 3:03 pm
#196591

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

0
0
Reply
Diane Poremsky(@diane-poremsky)
Author
Reply to  Arumugam
February 23, 2016 1:21 am
#196667

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.

0
0
Reply
Brent (@guest_192935)
August 27, 2015 12:46 pm
#192935

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 »

0
0
Reply
Brent (@guest_192928)
August 27, 2015 9:26 am
#192928

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.

0
0
Reply
Diane Poremsky(@diane-poremsky)
Author
Reply to  Brent
August 27, 2015 12:26 pm
#192933

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.

0
0
Reply
Brent (@guest_192913)
August 27, 2015 12:17 am
#192913

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!!!

0
0
Reply
Diane Poremsky(@diane-poremsky)
Author
Reply to  Brent
August 27, 2015 12:26 am
#192914

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))".

0
0
Reply

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

Latest EMO: Vol. 30 Issue 19

Subscribe to Exchange Messaging Outlook






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?

Our Sponsors

CompanionLink
ReliefJet
  • Popular
  • Latest
  • Week Month All
  • Jetpack plugin with Stats module needs to be enabled.
  • Open Outlook Templates using PowerShell
  • Count and List Folders in Classic Outlook
  • Google Workspace and Outlook with POP Mail
  • Import EML Files into New Outlook
  • Opening PST files in New Outlook
  • New Outlook: Show To, CC, BCC in Replies
  • Insert Word Document into Email using VBA
  • Delete Empty Folders using PowerShell
  • Warn Before Deleting a Contact
  • Classic Outlook is NOT Going Away in 2026
Ajax spinner

Recent Bugs List

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

For new Outlook for Windows: Fixes or workarounds for recent issues in new Outlook for Windows .

Outlook for Mac Recent issues: Fixes or workarounds for recent issues in Outlook for Mac

Outlook.com Recent issues: Fixes or workarounds for recent issues on Outlook.com

Office Update History

Update history for supported Office versions is at Update history for Office

Outlook Suggestions and Feedback

Outlook Feedback covers Outlook as an email client, including Outlook Android, iOS, Mac, and Windows clients, as well as the browser extension (PWA) and Outlook on the web.

Outlook (new) Feedback. Use this for feedback and suggestions for Outlook (new).

Use Outlook.com Feedback for suggestions or feedback about Outlook.com accounts.

Other Microsoft 365 applications and services




New Outlook Articles

Open Outlook Templates using PowerShell

Count and List Folders in Classic Outlook

Google Workspace and Outlook with POP Mail

Import EML Files into New Outlook

Opening PST files in New Outlook

New Outlook: Show To, CC, BCC in Replies

Insert Word Document into Email using VBA

Delete Empty Folders using PowerShell

Warn Before Deleting a Contact

Classic Outlook is NOT Going Away in 2026

Newest Code Samples

Open Outlook Templates using PowerShell

Count and List Folders in Classic Outlook

Insert Word Document into Email using VBA

Warn Before Deleting a Contact

Use PowerShell to Delete Attachments

Remove RE:, FWD:, and Other Prefixes from Subject Line

Change the Mailing Address Using PowerShell

Categorize @Mentioned Messages

Send an Email When You Open Outlook

Delete Old Calendar Events using VBA

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

VBOffice.net samples

SlovakTech.com

Outlook MVP David Lee

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

Diane Poremsky [Outlook MVP]

Make a donation

Mail Tools

Sending and Retrieval Tools

Mass Mail Tools

Compose Tools

Duplicate Remover Tools

Mail Tools for Outlook

Online Services

Calendar Tools

Schedule Management

Calendar Printing Tools

Calendar Reminder Tools

Calendar Dates & Data

Time and Billing Tools

Meeting Productivity Tools

Duplicate Remover Tools

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

Submit Outlook Feature Requests

Slipstick Support Services

Buy Microsoft 365 Office Software and Services

Visit Slipstick Forums.

What's New at Slipstick.com

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

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

wpDiscuz

Sign up for Exchange Messaging Outlook

Our weekly Outlook & Exchange newsletter (bi-weekly during the summer)






Please note: If you subscribed to Exchange Messaging Outlook before August 2019, please re-subscribe.

Never see this message again.

You are going to send email to

Move Comment