如何在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实例?

我知道如何做到这一点,当他们是同一个实例的一部分。 在这个特殊情况下,我需要将这两个工作簿放在不同的实例中。 我还需要做一个完整的副本(数据validation,公式,值,格式等),所以r2.Value = r1.Value是不够的。

在任何情况下都很难得到Excel的两个实例相互交谈。 你可以find其他正在运行的实例,但有太多东西需要考虑。

在类似的情况下,我保持简单,并做出两个button:

  • 导出保存到clipboard.csv或clipboard.xlsx或任何您喜欢的数据复制的格式
  • 从剪贴板临时文件获取数据的导入

用户负责在一个实例上单击“导出”button,然后在第二个实例上的“导入”button上执行操作。

我认为你需要详细说明为什么你需要单独的实例,到目前为止,在我的职业生涯中,我从来没有任何理由在Excel中使用单独的实例,这是自动化的噩梦。

这就是说,你可以给这样的尝试(假设你只有2个实例打开):

 Sub MM() Dim varTask As Variant Dim XL1 As Application, XL2 As Application Dim r1 As Range, r2 As Range Dim OtherWB As Workbook Dim destination_sanitized As String destination_sanitized = CreateObject("Scripting.FileSystemObject").BuildPath("C:\temp\", "1.xlsx") With CreateObject("Word.Application") If .Tasks.Exists("Microsoft Excel") Then For Each varTask In .Tasks Debug.Print varTask If InStr(varTask.Name, "Microsoft Excel") = 1 Then If XL1 Is Nothing Then Set XL1 = GetObject(Replace(varTask, "Microsoft Excel - ", "")).Application Else Set XL2 = GetObject(Replace(varTask, "Microsoft Excel - ", "")).Application End If End If Next varTask End If .Quit End With 'Then something like... Set r1 = ThisWorkbook.Sheets("hidden").Range("E10:E13") Set OtherWB = XL2.Workbooks.Open(destination_sanitized) Set r2 = OtherWB.Sheets("Sheet1").Range("J20:J23") r1.Copy r2 'Clear down memory afterwards Set r1 = Nothing Set r2 = Nothing OtherWB.Close False Set OtherWB = Nothing Set XL1 = Nothing XL2.Quit Set XL2 = Nothing End Sub