当您在 Excel 中复制时(复制的区域有行军蚂蚁边框),数据实际上并不在剪贴板上。粘贴时,Excel 使用剪贴板从源单元格实时传输。它这样做是为了在粘贴操作期间将公式重新编写为新的相对单元格引用。如果删除源单元格,则 Excel 在粘贴操作期间无法从中提取数据。
VBA 不支持直接使用剪贴板。但是,您可以将 MSForms 添加到 VBA 项目,然后声明一个支持剪贴板功能的对象。
有关如何直接从 VBA 访问剪贴板的说明和示例,请参见以下网站:
http://www.cpearson.com/excel/Clipboard.aspx
对我来说,我的可用列表中没有 MSForms references
,正如cpearson
网站上所建议的那样,但我确实在 C:\ 驱动器中搜索了 FM20.dll 并发现它隐藏在一些不起眼的文件夹中。我将它复制到 C:\ 的根目录,并且能够reference
通过单击对话框将其添加browse
为。add references
MSForms 可用后,您可以使用此代码将文本复制到剪贴板,该剪贴板在源单元格被删除后仍然存在。
Public Sub Test()
Dim obj As New MSForms.DataObject
obj.SetText ActiveCell.Value
obj.PutInClipboard
End Sub
这个复制了持续存在的公式:
Public Sub Test()
Dim obj As New MSForms.DataObject
obj.SetText ActiveCell.Formula
obj.PutInClipboard
End Sub
我没有时间弄清楚如何将单元格的格式复制到剪贴板,但如果您想保留复制的值以便可以将它们粘贴到源单元格之后,这似乎是您需要走的方向被删除。
编辑#1
Even though the Windows Clipboard can store multiple formats for one item (e.g., RTF and Text versions of a copied selection), it can only store one item at a time.
The Office Clipboard doesn't use the Windows Clipboard. It stores copied values itself, and can store many different selections. However, as of Office 2000, it could not be controlled via VBA (see How to use the Office 2000 Clipboard), and selections copied from Excel are either 'paste text' or 'paste all'. There is no paste special to just paste the formats. I couldn't find anything that says different for later versions of Office.
Conclusion: The only way to use VBA to do a paste special is to have an active / valid / copied selection. So I agree that the only solution is to declare your own persistent global variables (e.g., a list of objects) and store the formats for each copied selection in the list. Since the clipboard really isn't a viable solution, SetData
and SetDataObject
are irrelevant... If it proves impossible to capture the formatting of a cell in a single line of VBA code, you could always enumerate the formats of interest and set flags in your stored objects for later use.