VBA,激活工作簿而不显式命名它

时间:2018-12-10 16:31:58

标签: excel vba excel-vba

我的代码有工作簿A和工作簿B。我将工作表从B复制到A。问题是两者都将打开,因此我明确命名了每个工作簿。

当我粘贴到B中时,我会通过其名称激活A。无论如何,我可以不使用工作簿名称来激活A吗?

'Set Current Workbook as Master
Set masterWB = Application.ThisWorkbook
'Set some Workbook as the one you are copying from
Set dailyWB = Workbooks.Open(Sheets("Control Manager").Range("O2"))

'Copy the Range from dailyWB and Paste it into the MasterWB
dailyWB.Sheets("Summary").Range("A1:BJ200").Copy masterWB.Sheets("AFS Summary").Range("A1").Rows("1:1")
'formatting and paste as values
Workbooks("Workbook B").Activate
Worksheets("Summary").Select

1 个答案:

答案 0 :(得分:0)

如果您不想明确设置工作簿,则可以始终期待一些错误的空间。

但是,如果只有两个工作簿处于打开状态,则以下内容应允许您设置备用工作簿-否则,如果您有更多打开空间,则可能无法按预期工作。

Dim masterWB As Workbook, dailyWB As Workbook, wb As Workbook

Set masterWB = ThisWorkbook
For Each wb In Application.Workbooks
    If wb.Name <> masterWB.Name Then 
        Set dailyWB = wb
        exit for
    End if
Next

Debug.Print dailyWB.Name