22

我正在使用这样的代码从剪贴板中获取文本。

Dim DataObj As New MSForms.DataObject
DataObj.GetFromClipboard
myString = DataObj.GetText

我使用错误处理来解决剪贴板为空的情况,只要我将错误捕获设置为未处理错误时中断,一切都很好。

但是,由于不相关的原因,我想将错误捕获设置为在所有错误时中断,这会在DataObj.GetText找到空剪贴板时引发错误。是否有任何类型的测试我可以在上游进一步应用以避免尝试处理空剪贴板?

4

2 回答 2

28

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.dll64 位机器上找到),否则会出现错误“未定义用户定义的类型”

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

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
于 2012-01-26T19:44:08.457 回答
0

添加以下代码只是 b4 用于调试的断线....在那次测试之后错误对我来说消失了.. 奇怪但它以某种方式工作(Excel 2010)

myString = DataObj.GetText(1)
MsgBox myString
于 2017-02-01T18:22:41.263 回答