Paste clipboard contents using VBA

Last reviewed on December 30, 2013

I need a macro that adds a specific text, plus the content of my clipboard, at the end of the subject of all messages I have selected. How do I get the content of the clipboard automatically, without first pasting it into an Input Box?

Although Outlook VBA doesn't include a paste from clipboard function directly, you can use the MSForms dataobject to transfer the clipboard contents to a string which is then called from VBA.

You can also use Word's 'Keep Source Formatting' to paste formatted text into an Item Body. Code sample is at Paste formatted text using VBA

Add code similar to this to your macro:

 Dim DataObj As MSForms.DataObject
 Set DataObj = New MSForms.DataObject
 DataObj.GetFromClipboard

strPaste = DataObj.GetText(1)

The finished code will look something like the following. Note, you will need to have a reference to the Forms library in Tools, References.
Add the forms library as a reference
If you receive a "User-defined type not defined" you are missing the reference to Microsoft Forms 2.0 Object Library. If its not listed, add C:\Windows\System32\FM20.dll or C:\Windows\FM20.dll as a reference.

Sub AddtoSubject()
 Dim ex As Explorer
 Dim mail As MailItem
 Set ex = Application.ActiveExplorer
 Dim strPaste  As Variant
 
Dim DataObj As MSForms.DataObject
Set DataObj = New MSForms.DataObject
DataObj.GetFromClipboard

strPaste = DataObj.GetText(1)

If strPaste = False Then Exit Sub
If strPaste = "" Then Exit Sub

 For Each mail In ex.Selection
    mail.Subject = mail.Subject & " my text " & strPaste
    mail.Save
 Next mail
 
Set DataObj  = Nothing
End Sub

Copy to Clipboard

What about going in the other direction: copying text to the clipboard? Use PutInClipboard to capture the text.

Sub CapturetoClipbaord()
Dim oMail As MailItem
DataObj As MSForms.DataObject

    Set oMail = ActiveExplorer().Selection.Item(1)
    Set DataObj = New MSForms.DataObject
    DataObj.SetText oMail.Body
    DataObj.PutInClipboard
End Sub

Written by

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.

If the Post Coment button disappears, press your Tab key.