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

Search PDF Attachments and Forward

Slipstick Systems

› Developer › Code Samples › Search PDF Attachments and Forward

Last reviewed on March 10, 2021     2 Comments

A security update disabled the Run a script option in the rules wizard in Outlook 2010 and all newer Outlook versions. See Run-a-Script Rules Missing in Outlook for more information and the registry key to fix restore it.

This macro uses Adobe Acrobat, not Reader or other PDF applications.

This run a script macro will open an attached PDF file, look for a keyword and if found, forward the attachment.
forward pdf files using a rule

If the message you are forwarding contains external content, you may need to respond to a security dialog. In this case, you will need to use a new message and attach the file.

In this example the word you are looking for is the user's alias. If the user's full name as it appears in your contacts or global address list is in the attachment, you can use that as the address and Outlook will resolve it.

create a rule to forward messages

Dim strSaveTemp As String
Dim sendTo  As String

' use this in a rule
' Need to set a reference to Acrobat Type Library

Sub CheckAttachment(Item As Outlook.MailItem)
Dim oAtt As Attachment
strAtt = ""
sendTo = ""
searchString = ""

For Each oAtt In Item.Attachments

' check extension
If Right(oAtt.Filename, 4) = ".pdf" Then

' check filename
'If InStr(oAtt.FileName, "keyword") > 0 Then

strSaveTemp = "C:\Temp\" & oAtt.Filename
 oAtt.SaveAsFile (strSaveTemp)

searchPDF (strSaveTemp)

If sendTo <> "" Then

' forward message
Set myForward = Item.Forward

' create new message if forward contains external content
' and triggers a dialog
'Set myForward = Application.CreateItem(olMailItem)

With myForward
   .Recipients.Add sendTo
   .Subject = oAtt.Filename
   '.Attachments.Add strSaveTemp
   .Display 'for testing
'   .Send 
End With
   Exit Sub
' delete the temp file
   Kill strSaveTemp
End If

End If

' delete the temp file
Kill strSaveTemp

Next oAtt

End Sub

Sub searchPDF(strSaveTemp As String)

    Dim searchString As String
    Dim appObj As Object, AVDocObj As Object
    Dim arrSearch As Variant

    'Check if the file exists.
    If Dir(strSaveTemp) = "" Then
        MsgBox "File not found..."
        Exit Sub
    End If

    On Error Resume Next

    'Create Adobe Application object.
    Set appObj = CreateObject("AcroExch.App")

    'Check for any errors.
    If Err.Number <> 0 Then
        MsgBox "Error in creating the Adobe Application object..."
        Set appObj = Nothing
        Exit Sub
    End If

    'Create the AVDoc object.
    Set AVDocObj = CreateObject("AcroExch.AVDoc")

    'Check for any errors.
    If Err.Number <> 0 Then
        MsgBox "Error in creating the AVDoc object..."
        Set AVDocObj = Nothing
        Set appObj = Nothing
        Exit Sub
    End If

    On Error GoTo 0

    'Open the PDF file and check if the open was successful.
If AVDocObj.Open(strSaveTemp, "") = True Then
     Debug.Print strSaveTemp, searchString
        
' Set up the array these are the words you are searching for
arrSearch = Array("poremsky", "slipstick", "cdolive", "jackie", "s.smith", "jacksprat")

' Go through the array and look for a match, then do something
For i = LBound(arrSearch) To UBound(arrSearch)
        Debug.Print arrSearch(i)
        ' search string, case sensitive, whole words only, start search on page 1
        If AVDocObj.FindText(arrSearch(i), False, True, True) = True Then
   
   ' Set the To address or name
           sendTo = arrSearch(i) & "@domain.com"
         
         AVDocObj.Close True
        appObj.Exit
        'Release the objects.
        Set AVDocObj = Nothing
        Set appObj = Nothing
          Exit Sub
    Else: nofound = True
        End If
Next i
    
    If nofound = True Then
            'If text was not found, close the PDF file and perform clean-up
            AVDocObj.Close True
            appObj.Exit

            'Release the objects.
            Set AVDocObj = Nothing
            Set appObj = Nothing

' comment out or delete this line after testing. 
        MsgBox "The string not found in the PDF file..."
   
   End If

    Else
        'PDF file failed to open
        appObj.Exit

        'Release the objects.
        Set AVDocObj = Nothing
        Set appObj = Nothing

' comment out or delete this line after testing. 
        MsgBox "Could not open the PDF file..."

    End If

End Sub

If the search word can't used as the To address, you need to use a second array to add the address.

Dim arrTo As Variant

' Set up the array
arrSearch = Array("poremsky", "slipstick", "search3", "search4", "search5", "search6", "search7")

' if the search word can't be used as the To address, you need to use a second array.
arrTo = Array("alias@domain.com", "alias2@domainx.com", "To3", "To4", "To5", "To6", "To7")

' Go through the array and look for a match, then do something
For i = LBound(arrSearch) To UBound(arrSearch)
        Debug.Print arrSearch(i)
        ' search string, case sensitive, whole words only, start at beginning
        If AVDocObj.FindText(arrSearch(i), False, False, True) = True Then
          
        sendTo = arrTo(i)
         
         AVDocObj.Close True
        appObj.Exit
        'Release the objects.
        Set AVDocObj = Nothing
        Set appObj = Nothing
          Exit Sub
    Else: nofound = True
        End If
Next i

 

Test the Rule

You can use this script to test the macro on a message in your mailbox, rather than sending yourself messages to see if the rule works. You can also use this to run the script on messages manually.

To use: paste into the module, select a message and run this macro.

' use this to test the script - select a message and run this macro
Sub RunCheckAttachment()
Dim objApp As Outlook.Application
Dim objItem As Object ' MailItem
Set objApp = Application
Set objItem = objApp.ActiveExplorer.Selection.Item(1)

'macro name you want to run goes here
CheckAttachment objItem

End Sub

How to use the macros on this page

First: You need to have macro security set to the lowest setting, Enable all macros during testing. The macros will not work with the top two options that disable all macros or unsigned macros. You could choose the option Notification for all macros, then accept it each time you restart Outlook, however, because it's somewhat hard to sneak macros into Outlook (unlike in Word and Excel), allowing all macros is safe, especially during the testing phase. You can sign the macro when it is finished and change the macro security to notify.

To check your macro security in Outlook 2010 and newer, go to File, Options, Trust Center and open Trust Center Settings, and change the Macro Settings. In Outlook 2007 and older, look at Tools, Macro Security.

After you test the macro and see that it works, you can either leave macro security set to low or sign the macro.

Macros that run when Outlook starts or automatically need to be in ThisOutlookSession, all other macros should be put in a module, but most will also work if placed in ThisOutlookSession. (It's generally recommended to keep only the automatic macros in ThisOutlookSession and use modules for all other macros.) The instructions are below.

The macros on this page should be placed in a module.

Open the VBA Editor by pressing Alt+F11 on your keyboard.

To put the code in a module:

  1. Right click on Project1 and choose Insert > Module
  2. Copy and paste the macro into the new module.

Set a reference to other Object Libraries
If you receive a "User-defined type not defined" error, you need to set a reference to another object library.

  1. Go to Tools, References menu.
  2. Locate the Adobe object library in the list and add a check mark to it. (Word and Excel object libraries version numbers will match Outlook's version number.)
    Reference the Word object model in Outlook's VBA Editor

More information as well as screenshots are at How to use the VBA Editor

Search PDF Attachments and Forward was last modified: March 10th, 2021 by Diane Poremsky

Related Posts:

  • Check for missing attachments before sending a message
  • Remove Attachments From Messages
  • Macro to Print Outlook email attachments as they arrive
  • Rename Outlook Attachments

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
2 Comments
newest
oldest most voted
Inline Feedbacks
View all comments

ROGER SVENDSEN
August 24, 2021 2:19 pm

How does one search for a string that crosses a line boundary?

0
0
Reply
Steve Pattyson
March 16, 2021 4:28 pm

Diane Poremsky's abilities and focus blow me away. She has brought me back from the edge of computer despair more than once. I understand 1 out of every 60 words she publishes. I think she is from another, more advanced planet.

0
0
Reply

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

Latest EMO: Vol. 30 Issue 36

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
  • Use Classic Outlook, not New Outlook
  • How to Remove the Primary Account from Outlook
  • How to Hide or Delete Outlook's Default Folders
  • Removing Suggested Accounts in New Outlook
  • Reset the New Outlook Profile
  • This operation has been cancelled due to restrictions
  • iCloud error: Outlook isn't configured to have a default profile
  • Adjusting Outlook's Zoom Setting in Email
  • Online Services in Outlook: Gmail, Yahoo, iCloud, AOL, GoDaddy
  • Add Holidays to Outlook's Calendar
  • Opt out of Microsoft 365 Companion Apps
  • Mail Templates in Outlook for Windows (and Web)
  • Urban legend: Microsoft Deletes Old Outlook.com Messages
  • Buttons in the New Message Notifications
  • Move Deleted Items to Another Folder Automatically
  • 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
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

Opt out of Microsoft 365 Companion Apps

Mail Templates in Outlook for Windows (and Web)

Urban legend: Microsoft Deletes Old Outlook.com Messages

Buttons in the New Message Notifications

Move Deleted Items to Another Folder Automatically

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

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.

:wpds_smile::wpds_grin::wpds_wink::wpds_mrgreen::wpds_neutral::wpds_twisted::wpds_arrow::wpds_shock::wpds_unamused::wpds_cool::wpds_evil::wpds_oops::wpds_razz::wpds_roll::wpds_cry::wpds_eek::wpds_lol::wpds_mad::wpds_sad::wpds_exclamation::wpds_question::wpds_idea::wpds_hmm::wpds_beg::wpds_whew::wpds_chuckle::wpds_silly::wpds_envy::wpds_shutmouth:
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