Excel VBA code to copy a specific string to clipboard

user1958738 picture user1958738 · Jan 8, 2013 · Viewed 165.5k times · Source

I'm trying to add a button to a spreadsheet that when clicked will copy a specific URL to my clipboard.

I had a bit of knowledge of Excel VBA but it's been a while and I'm struggling.

Answer

Jroonk picture Jroonk · Aug 16, 2014

This macro uses late binding to copy text to the clipboard without requiring you to set references. You should be able to just paste and go:

Sub CopyText(Text As String)
    'VBA Macro using late binding to copy text to clipboard.
    'By Justin Kay, 8/15/2014
    Dim MSForms_DataObject As Object
    Set MSForms_DataObject = CreateObject("new:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
    MSForms_DataObject.SetText Text
    MSForms_DataObject.PutInClipboard
    Set MSForms_DataObject = Nothing
End Sub

Usage:

Sub CopySelection()
    CopyText Selection.Text
End Sub