使用 GetText 从剪贴板获取文本 - 避免在空剪贴板上出错 [英] Get text from clipboard using GetText - avoid error on empty clipboard
问题描述
我正在使用这样的代码从剪贴板中获取文本.
I'm using code like this to get text from off the Clipboard.
Dim DataObj As New MSForms.DataObject
DataObj.GetFromClipboard
myString = DataObj.GetText
我使用错误处理来避免剪贴板为空的情况,只要我将错误捕获设置为中断未处理的错误,一切都很好.
I use error handling to get the past the case where the Clipboard is empty, and everything is fine as long as I keep Error Trapping set to Break on Unhandled Errors.
但是,由于不相关的原因,我想将错误捕获设置为在所有错误上中断,当它找到空剪贴板时,这会在 DataObj.GetText
处引发错误.是否有任何类型的测试可以进一步应用于上游以避免尝试处理空剪贴板?
However, for unrelated reasons I want to set Error Trapping to Break on All Errors, and this throws an error at DataObj.GetText
when it finds the empty Clipboard. Is there any kind of test I can apply further upstream to avoid trying to process an empty Clipboard?
推荐答案
使用 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.dll
或 C: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
这篇关于使用 GetText 从剪贴板获取文本 - 避免在空剪贴板上出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!