8

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:

enter image description here

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

Jon
  • 814
  • 2
  • 8
  • 11
  • It would help if you show us the code you're using that's causing the problem, as well as the error message it's generating. – Cindy Meister Feb 24 '16 at 08:29
  • @CindyMeister: Thank you Cindy. I added the information you requested, but note that I answered my own question from the start. This was a problem I faced several years ago, and the method in my answer was the best one that I found and doesn't rely on error handling. It works very well for me. – Jon Feb 24 '16 at 08:48
  • I missed that you answered your own question - good contribution :-) Thanks for adding the additional information, I think it adds to the value of the question (makes it clearer). – Cindy Meister Feb 24 '16 at 09:06
  • @CindyMeister: I really should have said **worked** very well for me as I really don't use the `.Paste` method anymore. I typically work with ranges and then will put the text in place with something like `myRangeVariable.Text = "some text"`. I may be misguided, but I think that way is faster. But I know that when I needed to paste, it was difficult trying to deal with the empty clipboard problem. And I preferred not to do it with error handling. – Jon Feb 24 '16 at 10:02
  • 1
    Assign Range.Text = Range.Text is indeed faster and has the advantage of not interfering with what the user may have put on the Clipboard. Or Range.FormattedText = Range.FormattedText when the formatting is important. Different, of course, when an external application (Excel, for example) is involved... – Cindy Meister Feb 24 '16 at 10:16

1 Answers1

7

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).

enter image description here

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
Jon
  • 814
  • 2
  • 8
  • 11