[英]How can I copy between two open Excel instances in VBA?
我想將已打開的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是不夠的。
我認為你需要詳細說明為什么你需要單獨的實例,到目前為止,在我的職業生涯中,我從來沒有任何理由在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
在所有情況下,很難讓兩個Excel實例相互通信。 您可以找到其他正在運行的實例,但需要考慮的事情太多。
在類似的情況下,我保持簡單,並制作兩個按鈕:
用戶負責單擊一個實例上的“導出”按鈕,然后單擊第二個實例上的“導入”按鈕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.