How can I copy between two open instances of Excel in VBA?

I want to copy data from one already open 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 a "1004" runtime error: Failed to execute copy method of Range class

How to copy data from one already open instance of Excel to another instance of Excel in VBA?

I understand how to do this when they are part of the same instance. In this particular case, I need the two books to be in separate copies. I also need to make a full copy (checking data, formulas, values, formats, etc.), Therefore r2.Value = r1.Value will not be sufficient.

+5
source share
2

, , , 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
+1

Excel, . , , .

:

  • , clipboard.csv clipboard.xlsx
  • ,

"" , "" .

+1

All Articles