我正在尝试构建一个代码,该代码将切换到其他打开的工作簿并从那里复制数据。
我可以使用工作簿(1)和工作簿(2),但问题是这个索引按开放工作簿的顺序改变。
所以我想将if函数放入其中,但不起作用。以下是代码。
If ActiveWorkbook = Workbooks(1) Then
Workbooks(2).Activate
Else
Workbooks(1).Activate
End If
但是它给出了错误438,对象不支持属性或方法。
你能帮我调试吗?
答案 0 :(得分:2)
请尝试以下代码,复制>>的最后一部分粘贴只是一个示例,您将Range("A1:E10")
从DestWB
中的“Sheet1”复制到ThisWB
“Sheet1”(不使用Activate
或Select
) - 你应该能够很容易地修改它。
<强>代码强>
Option Explicit
Sub CopyThisWorkBOok()
Dim ThisWB As Workbook
Dim DestWB As Workbook
Dim wb As Workbook
Dim i As Long
i = Application.Workbooks.Count
If i <> 2 Then ' check if number of open workbooks is 2
MsgBox "You need to have 2 open workbooks, currently there are " & i & " open workbooks", vbCritical
Exit Sub
Else
For Each wb In Application.Workbooks ' loop through all open workbooks
If wb.Name <> ThisWorkbook.Name Then
Set DestWB = wb
Else
Set ThisWB = ThisWorkbook
End If
Next wb
End If
' from here you start the part where you copy >> paste, there is no need to `Activate` or `Select` anything
DestWB.Worksheets("Sheet1").Range("A1:E10").Copy Destination:=ThisWB.Worksheets("Sheet1").Range("A2")
End Sub
答案 1 :(得分:0)
您可以使用目标对象的名称,例如:
Workbooks("MyBook.xls").Worksheets("Sheet1").Activate
答案 2 :(得分:0)
根据您要执行的操作,描述不是很清楚,您可以使用此代码的变体。您可以将包含VBA的工作簿定义为“ThisWorkBook”并从那里开始。
Dim source_worksheet As Worksheet
Set source_worksheet = ThisWorkbook.Worksheets("Sheet2")
Dim target_worksheet As Worksheet
Set target_worksheet = ActiveWorkbook.Worksheets("Sheet1")
'Defines what sheet you are copying
source_worksheet.Copy After:=target_worksheet