vba 如何将单元格的内容复制到剪贴板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/710435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 10:20:19  来源:igfitidea点击:

How do you copy the contents of a Cell into the Clipboard

excel-vbavbaexcel

提问by Brian Boatright

I'm trying to copy the cell contents into the clipboard.

我正在尝试将单元格内容复制到剪贴板中。

I've read and tried the exact example provided in the Excel 2007 Help file. However for some reason the DataObject object is not valid. So the example:

我已阅读并尝试了 Excel 2007 帮助文件中提供的确切示例。但是由于某种原因,DataObject 对象无效。所以这个例子:

Dim MyData As DataObject

Private Sub CommandButton1_Click()
    Set MyData = New DataObject

    MyData.SetText TextBox1.Text
    MyData.PutInClipboard

    TextBox2.Paste
End Sub

Private Sub UserForm_Initialize()
    TextBox1.Text = "Move this data to a " _
        & "DataObject, to the Clipboard, then to " _
        & "TextBox2!"
End Sub

Does not work in my case. I've searched for a good while now and I can not find an answer to why the DataObject object is not available.

在我的情况下不起作用。我已经搜索了一段时间,但找不到 DataObject 对象为何不可用的答案。

Here is my code:

这是我的代码:

Dim MyData As DataObject

Private Sub Worksheet_Change(ByVal Target As Range)
    If ActiveCell.Column = 3 Then
        Set MyData = New DataObject
        MyData.SetText ActiveCell.Offset(-1, -1).Text
        MyData.PutInclipboard
    End If    
End Sub

Error on Compile is: "User-Defined type not defined" and it highlights the "MyData As DataObject" line.

编译错误是:“未定义用户定义的类型”,它突出显示了“MyData As DataObject”行。

Is there another method to simply copying the text in a cell to the clipboard?

是否有另一种方法可以简单地将单元格中的文本复制到剪贴板?

回答by curtisk

Ok, few things:

好的,有几点:

First you need to Add a reference to "Microsoft Forms 2.0 Object Library", if you don't feel like searching through, just add a user form to the project and then immediately delete it, the reference will stay. You need that reference to use DataObject

首先您需要添加对“Microsoft Forms 2.0 Object Library”的引用,如果您不想搜索,只需在项目中添加一个用户表单然后立即将其删除,引用将保留。您需要该引用才能使用 DataObject

I'll attach some code that I got to work, I changed the offsets but make them whatever you need...

我会附上一些我开始工作的代码,我改变了偏移量,但根据你的需要制作它们......

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Set MyData = New DataObject
    If ActiveCell.Column = 3 Then
        MyData.SetText ActiveCell.Offset(-1, 0).Text
        MyData.PutInClipboard
    End If
End Sub