Reading from Clipboard

Vishesh's picture
The following piece of code displays any text which is there in the clipboard. To try it paste the following code in the general module. Select any text from anywhere and press Ctrl+C to copy to clipboard. Now, run the following code. It will display what you selected and copied to clipboard using Ctrl+C.
Sub GetTextFromClipboard()
    'For DataObject add reference to Microsoft Forms 2.0 Object Library
    'If you cannot find this library just add a userform and
    'now you will find the library reference. Check it.
    
    Dim objClipBoard        As DataObject
    Dim lngCounter          As Long
 
    Set objClipBoard = New DataObject
    objClipBoard.GetFromClipboard
 
    For lngCounter = 1 To UBound(Application.ClipboardFormats)
        If Application.ClipboardFormats(lngCounter) = xlClipboardFormatText Then
            MsgBox objClipBoard.GetText(lngCounter)
        End If
    Next lngCounter
 
    Set objClipBoard = Nothing
End Sub
Vishesh's picture

Reading from Clipboard - Optimised

Sub GetTextFromClipboard()
    'No Library Reference required.
    
    Dim objClipBoard        As Object
    Dim lngCounter          As Long
 
    Set objClipBoard = CreateObject("new:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
    objClipBoard.GetFromClipboard
 
    For lngCounter = 1 To UBound(Application.ClipboardFormats)
        If Application.ClipboardFormats(lngCounter) = xlClipboardFormatText Then
            MsgBox objClipBoard.GetText(lngCounter)
        End If
    Next lngCounter
 
    Set objClipBoard = Nothing
End Sub