VBA 更改活动工作簿

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12386448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 14:00:19  来源:igfitidea点击:

VBA changing active workbook

excelvba

提问by mezamorphic

I have a spreadsheet where in the VBA it goes off opening other spreadsheets and temporarily setting these to the active worksheet.

我有一个电子表格,在 VBA 中它会打开其他电子表格并暂时将它们设置为活动的worksheet.

However, I have a loop and at the end of the first iteration I need to set the active worksheet to be the original one which started the VBA module. I cannot set a new Workbookobject to open the original, because the original is still open in the background and it says its already open.

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

My problem is that I need to change the active Workbookto the original one, when I never had a workbook object to refer to it???

我的问题是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

回答by brettdj

Use ThisWorkbookwhich will refer to the original workbook which holds the code.

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

Alternatively at code start

或者在代码开始时

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

在返回之前激活所有打开的书籍的示例代码 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