Search code examples
vbatextformatclipboard

VBA store formatted text in clipboard


I need to copy/store a string of text into the clipboard but need that text to be formatted (font type, color, weight, etc.)

Private Sub copyToCB(varText As String)
    Dim x As Variant
    x = varText

    CreateObject("htmlfile").parentWindow.clipboardData.setData "text", x
End Sub

The above does the job of storing the referred text into the clipboard but it's stored as plain text. I'd like it to be e.g. bold and red.

I've been scouring the Internet literally for hours, to no avail. You'd think this would be something straightforward but I'm at a total loss!


Solution

  • If you use the clipboard classes from @GMCB found at https://stackoverflow.com/a/63735992/478884

    You can do this:

    Sub TestCopying()
        CopyWithSomeFormatting "This should paste as red/bold"
    End Sub
    
    Sub CopyWithSomeFormatting(txt As String)
        Dim myClipboard As New vbaClipboard 'Instantiate a vbaClipboard object
        myClipboard.SetClipboardText _
            "<span style='color:#F00;font-weight:bold'>" & txt & "</span>", "HTML Format"
    End Sub
    

    Works for me at least when pasting to Word/Excel