如何从剪贴板复制和复制到剪贴板?

How to copy from and to clipboard?

我有两个代码(在其他用户的帮助下):
#1 使用当前范围制作一个特定的文本字符串并将其放入剪贴板。
#2 从剪贴板复制,删除一些不需要的字符并将修改后的字符串放回剪贴板。

这些代码在某些公司机器上不起作用。
都检查了 Microsoft Forms 2.0 Object 库。

我读过有关使用 HTML 方法的信息,但我无法理解。

代码如下:

#1

Sub x_copiar_nome_arquivo()

    Dim DataObj As New MSForms.DataObject
    Dim arquivo As String
    
    On Error GoTo ErrorHandler
    With Selection.Rows(1).EntireRow
        arquivo = .Range("G1").Value & " - " & Format(.Range("E1").Value, "#000000000")
    End With
    With DataObj
        .SetText arquivo
        .PutInClipboard
    End With
    
ErrorHandler:
    Exit Sub
    
End Sub

#2

Sub y_chave_danfe()
    
    Dim DataObj As New MSForms.DataObject
    Dim chave As String
    Dim danfe As String
    
    On Error GoTo ErrorHandler
    DataObj.GetFromClipboard
    chave = DataObj.GetText
    danfe = Replace(Replace(Replace(Replace(Replace(chave, " ", ""), "/", ""), "-", ""), ".", ""), "_", "")
    With DataObj
        .SetText danfe
        .PutInClipboard
    End With
    
ErrorHandler:
    Exit Sub
    
End Sub

阿方索

您可以尝试将 late binding 用于 MSForms.DataObject

此代码应该适用于所有机器,无论它们是否具有适当的参考。

Sub y_chave_danfe()
Dim DataObj As Object
Dim chave As String
Dim danfe As String

    Set DataObj = CreateObject( _
                 "new:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
    On Error GoTo ErrorHandler
    DataObj.GetFromClipboard
    chave = DataObj.GetText
    danfe = Replace(Replace(Replace(Replace(Replace(chave, " ", ""), "/", ""), "-", ""), ".", ""), "_", "")
    With DataObj
        .SetText danfe
        .PutInClipboard
    End With

ErrorHandler:
    Exit Sub

End Sub

这是我编写的两个程序,您可以使用它们与剪贴板进行交互。

Function FromClipboard() As String
    'Returns all text currently in the user's clipboard
    Dim CB As Object
    Set CB = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
    CB.GetFromClipboard
    FromClipboard = CB.GetText
End Function

Sub IntoClipboard(ByVal Text As Variant)
    'Text is a Variant type for 64-Bit Support, but the content should be a String
    CreateObject("htmlfile").parentWindow.clipboardData.setData "text", Text
End Sub

这是一个如何使用它的例子

Sub test()
    'Before changes
    MsgBox FromClipboard
    
    'changing the text
    IntoClipboard "Testing"
    
    'After changes
    MsgBox FromClipboard
End Sub

该地址 1C3B4210-F441-11CE-B9EA-00AA006B1A69 适用于 Windows 但不适用于 Mac,如果您希望它适用于 Mac,您需要为它们找到正确的地址,然后在里面放一个 If/Else。