如何在 VBA 中的两个打开的 Excel 实例之间进行复制?
我想将数据从一个已打开的 Excel 实例复制到 VBA 中的另一个 Excel 实例。我尝试过:
Option Explicit
Sub copy_paste()
Dim destination_sanitized As String
Dim fs As New FileSystemObject
destination_sanitized = fs.BuildPath("c:\temp\", "1.xlsx")
Dim xl As New Excel.Application
Dim wb As Workbook
Set wb = xl.Workbooks.Open(Filename:=destination_sanitized)
Dim r1 As Range
Dim r2 As Range
Set r1 = ThisWorkbook.Sheets("hidden").Range("E10:E13")
Set r2 = wb.Sheets("Sheet1").Range("J20:J23")
On Error GoTo Cleanup
r1.Copy r2
Cleanup:
wb.Close SaveChanges:=False
Set xl = Nothing
MsgBox Err.Number & ": " & Err.description
End Sub
我收到运行时错误“1004”:Range 类的复制方法失败
如何将数据从一个已打开的 Excel 实例复制到 VBA 中的另一个 Excel 实例?
我知道当它们属于同一实例时如何执行此操作。在这种特殊情况下,我需要将两个工作簿放在不同的实例中。我还需要做一个完整的副本(数据验证、公式、值、格式等),所以 r2.Value = r1.Value 是不够的。
I want to copy data from one already opened instance of Excel to another instance of Excel in VBA. I tried:
Option Explicit
Sub copy_paste()
Dim destination_sanitized As String
Dim fs As New FileSystemObject
destination_sanitized = fs.BuildPath("c:\temp\", "1.xlsx")
Dim xl As New Excel.Application
Dim wb As Workbook
Set wb = xl.Workbooks.Open(Filename:=destination_sanitized)
Dim r1 As Range
Dim r2 As Range
Set r1 = ThisWorkbook.Sheets("hidden").Range("E10:E13")
Set r2 = wb.Sheets("Sheet1").Range("J20:J23")
On Error GoTo Cleanup
r1.Copy r2
Cleanup:
wb.Close SaveChanges:=False
Set xl = Nothing
MsgBox Err.Number & ": " & Err.description
End Sub
I get Run-time error '1004': Copy method of Range class failed
How can I copy data from one already opened instance of Excel to another Excel instance in VBA?
I understand how to do this when they are part of the same instance. In this particular case, I need the two workbooks to be in separate instances. I also need to do a full copy (Data Validation, Formulas, Values, Formats, etc), so r2.Value = r1.Value will not suffice.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您需要详细说明为什么需要单独的实例,到目前为止,在我的职业生涯中,我从未有任何理由在 Excel 中使用单独的实例,这对于自动化来说是一场噩梦。
话虽这么说,您可以尝试这样的操作(假设您只打开了 2 个实例):
I think you need to elaborate as to why you need separate instances, so far in my career I have never had any reason to use a separate instance in Excel and it is a nightmare for automation.
That being said, you can give something like this a try (assuming you only have 2 instances open):
让两个 Excel 实例在所有情况下都能相互通信是很困难的。您可以找到其他正在运行的实例,但要考虑的事情太多了。
在类似的情况下,我会保持简单并制作两个按钮:
格式化您想要复制的数据
用户负责单击一个实例上的“导出”按钮,然后单击第二个实例上的“导入”按钮。
It is difficult to get two instances of Excel to talk to each other in all situations. You can find the other running instances, but there are too many things to consider.
In similar cases I keep it simple and make two buttons:
format you like the data to copy
The user is in charge of clicking on the Export button on one instance, then on the Import button on the second instance.