且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 GetText 从剪贴板获取文本 - 避免在空剪贴板上出错

更新时间:2023-09-11 19:47:22

使用 On Error GoTo 处理错误,如下所示:

Handle the errors with On Error GoTo as shown here:

Sub GetClipBoardText()
   Dim DataObj As MSForms.DataObject
   Set DataObj = New MsForms.DataObject '<~~ Amended as per jp's suggestion

   On Error GoTo Whoa

   '~~> Get data from the clipboard.
   DataObj.GetFromClipboard

   '~~> Get clipboard contents
   myString = DataObj.GetText(1)
   MsgBox myString

   Exit Sub
Whoa:
   If Err <> 0 Then MsgBox "Data on clipboard is not text or is empty"
End Sub

你会注意到它也会处理一个空的剪贴板.

You will notice that it will handle an empty clipboard as well.

注意:要使代码工作,您必须有参考 到Microsoft Forms 2.0 对象库"(此文件可以在 32 位机器上的 C:windowssystem32FM20.dllC:WindowssysWOW64FM20.dll 上找到64 位机器),否则您会收到错误未定义用户定义的类型".

NB: to make the code work, you must have a reference to "Microsoft Forms 2.0 Object Library" (this file can be found at C:windowssystem32FM20.dll on 32-bit machines, or at C:WindowssysWOW64FM20.dll on 64-bit machines), otherwise you'd get the error "User-Defined type not defined".

您可以在使用以下代码测试上述代码之前清空剪贴板.请将其粘贴到模块中.

You can empty the clipboard before testing the above code by using the code below. Please paste it in a module.

Private Declare Function OpenClipboard Lib "User32.dll" _
(ByVal hWndNewOwner As Long) As Long
  
Private Declare Function EmptyClipboard Lib "User32.dll" () As Long
 
Private Declare Function CloseClipboard Lib "User32.dll" () As Long
 
Public Sub ClearClipboard()
    Dim Ret
  
    Ret = OpenClipboard(0&)
    If Ret <> 0 Then Ret = EmptyClipboard
    CloseClipboard
End Sub

您还可以使用以下代码确定剪贴板是否为空:

you may also determine if the clipboard is empty by using this code:

Private Declare Function CountClipboardFormats Lib "user32" () As Long

Sub Sample()
    If (CountClipboardFormats() = 0) = True Then
        MsgBox "Clipboard is empty"
    Else
        MsgBox "Clipboard is not empty"
    End If
End Sub