On Error GoTo
如下所示处理错误:
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
你会注意到它也会处理一个空的剪贴板。
注意:要使代码正常工作,您必须参考“Microsoft Forms 2.0 Object Library”(该文件可以C:\windows\system32\FM20.dll
在 32 位机器或C:\Windows\sysWOW64\FM20.dll
64 位机器上找到),否则会出现错误“未定义用户定义的类型”。
您可以使用以下代码在测试上述代码之前清空剪贴板。请将其粘贴到模块中。
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
编辑:您还可以使用以下代码确定剪贴板是否为空:
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