VBA更改活动工作簿

时间:2012-09-12 10:45:17

标签: excel vba

我有一个电子表格,在VBA中,它会打开其他电子表格并暂时将这些电子表格设置为有效的worksheet

但是,我有一个循环,在第一次迭代结束时,我需要将活动工作表设置为启动VBA模块的原始工作表。我无法设置新的Workbook对象来打开原始对象,因为原始文件仍然在后台打开并且它已经打开了。

我的问题是我需要将活动Workbook更改为原始版本,当我从未有过工作簿对象来引用它时?

'Original workbook is active implicitly

'loop begins

'change active workbook to something else


'Need to change back to original workbook here- but don't have a VBA workbook object

'end of loop

1 个答案:

答案 0 :(得分:17)

使用ThisWorkbook,它将引用包含代码的原始工作簿。

或者在代码开始时

Dim Wb As Workbook
Set Wb = ActiveWorkbook

示例代码,在返回ThisWorkbook之前激活所有打开的图书

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub