我正在使用这样的代码从剪贴板中获取文本。
Dim DataObj As New MSForms.DataObject
DataObj.GetFromClipboard
myString = DataObj.GetText
我使用错误处理来解决剪贴板为空的情况,只要我将错误陷阱设置为未处理错误的中断,一切都很好。
但是,由于无关的原因,我想将错误陷阱设置为中断所有错误,并且当它找到空剪贴板时会在DataObj.GetText
处引发错误。是否有任何类型的测试可以进一步应用于上游以避免尝试处理空剪贴板?
答案 0 :(得分:17)
这有帮助吗?
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
你会发现它也会处理一个空的剪贴板。
您可以在使用以下代码测试上述代码之前清空剪贴板。请将其粘贴到模块中。
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
编辑:OP的新请求
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
答案 1 :(得分:5)
希望这有助于其他人:
我在发布的代码上收到错误“用户定义的类型未定义” 亚洲时报Siddharth-击溃
原来“Microsoft Forms 2.0对象库”库缺失/未激活。
使用它(http://excel-macro.tutorialhorizon.com/vba-excel-reference-libraries-in-excel-workbook/):
“有时你不会在列表中找到所需的引用,比如在工具/引用列表中找不到”Microsoft Forms 2.0 Object Library“,在这种情况下你需要从中查看FM20.DLL文件SYSTEM32"
答案 2 :(得分:0)
添加下面的代码,只是b4用于调试的破解线......在测试之后,错误消失了我很奇怪但它有点工作(Excel 2010)
myString = DataObj.GetText(1)
MsgBox myString