【问题标题】:Get text from clipboard using GetText - avoid error when only graphic on clipboard使用 GetText 从剪贴板获取文本 - 当剪贴板上只有图形时避免错误
【发布时间】:2012-03-25 06:57:49
【问题描述】:

这是我在这里提出的问题的扩展:

Get text from clipboard using GetText - avoid error on empty clipboard

该问题的答案可以很好地避免空剪贴板出现错误,但现在我发现我还必须处理一个只包含图形而没有文本的剪贴板,并且这种情况超出了空剪贴板过滤器。

那么,当剪贴板上只有图形而没有文本时,如何中止该过程?

【问题讨论】:

    标签: error-handling excel clipboard excel-2003 vba


    【解决方案1】:

    您可以使用此代码测试剪贴板中数据的格式是否为图像。

    Option Explicit
    
    Private Declare Function OpenClipboard Lib "user32" _
    (ByVal hwnd As Long) As Long
    
    Private Declare Function GetClipboardData Lib "user32" _
    (ByVal wFormat As Integer) As Long
    
    Private Declare Function CloseClipboard Lib "user32" () As Long
    
    Const CF_BITMAP = 2
    
    Sub Sample()
        Dim RetClpB As Long
        Dim RetBmp As Long
    
        '~~> Open Clipboard
        RetClpB = OpenClipboard(0&)
    
        '~~> Check if we were successful
        If RetClpB <> 0 Then
            '~~> Test if the data in Clipboard is an image by
            '~~> trying to get a handle to the Bitmap
            RetBmp = GetClipboardData(CF_BITMAP)
    
            '~~> If found
            If RetBmp <> 0 Then
                MsgBox "data in clipboad is an image"
            Else
                MsgBox "data in clipboad is not an image"
            End If
        End If
    
        '~~> Close Clipboard
        RetClpB = CloseClipboard
    End Sub
    

    【讨论】:

    • 感谢 Siddharth,但这只能找到位图,我需要检测任何可以占用剪贴板上图片槽的图形对象。实际上,我认为我与最初的问题相去甚远,即在尝试使用 GetText 阅读之前检测剪贴板上是否有文本。查看 ClipboardFormats 属性的 VBA 帮助,如果不求助于 API,我们就不能用它做点什么吗?
    • 我感兴趣的唯一格式是 xlClipboardFormatText。无论剪贴板上还有什么,如果该格式不可用,那么我想中止该过程。当错误捕获设置为所有错误时中断时,这需要在不引发错误的情况下完成。我知道这里有一个答案只是想出去:)
    【解决方案2】:

    嗯,这需要一段时间,但这里是如何做到这一点。

    只是为了重申问题,我想使用 DataObject.GetFromClipboard 从剪贴板中提取文本,并将错误捕获设置为 Break on All Errors,并且在剪贴板上找不到文本时不会引发错误。

     Sub TEST_getClipText()
        Debug.Print getClipText
     End Sub
     Function getClipText() As String
        Dim DataObj As MsForms.DataObject
        Set DataObj = New MsForms.DataObject 'tnx jp
        Dim V As Variant
        For Each V In Application.ClipboardFormats
           If V = xlClipboardFormatText Then
              DataObj.GetFromClipboard
              getClipText = DataObj.getText(1)
              Exit Function
           End If
        Next V
        MsgBox "No text on clipboard"
     End Function
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    相关资源
    最近更新 更多