How to check if clipboard is empty of text?

2019-01-25 20:40发布

问题:

If I try to paste from an empty clipboard, I get an error. I would like to check if the clipboard is empty of text before pasting so that I can avoid this. How can this be accomplished? I'm aware it can be done through error handling, but I would prefer a method that avoids an error.

Edit -- Per request, adding code that creates the error and the error message:

Code that causes the problem:

Sub PasteFromEmptyClipBoard()

    Selection.Paste

End Sub

Error message that I get:

"Run-time error '4605' This method or property is not available because the Clipboard is empty or is not valid."

回答1:

Very important: You must first set a reference to the "Microsoft Forms 2.0 Object Library" (as in the attached screenshot below) before implementing this code. You may find that it is not an option when you scroll through the reference libraries. To make it show up, just add a form to the project (you can always delete the form later).

Sub CheckClipboard()

        Dim myDataObject As DataObject

        Set myDataObject = New DataObject


        myDataObject.GetFromClipboard


        If myDataObject.GetFormat(1) = True Then 

            '''There is text on clipboard, so it's safe to paste

        Else 
            '''there is no text on the clipboard, so you may get error.

        End If

End Sub