如何使用 Excel VBA 将 ActiveWorkbook 带到窗口的前面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44267126/
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-12 12:39:43  来源:igfitidea点击:

How to bring ActiveWorkbook to the front of the window using Excel VBA?

excelvbaexcel-vba

提问by Nicholas

I find that Workbook.Activatedoesn't always bring that workbook to the front of the window. I wonder what is the right way to set a workbook as the top of the window so when the macro is finished this is the workbook you are looking at.

我发现这Workbook.Activate并不总是把工作簿带到窗口的前面。我想知道将工作簿设置为窗口顶部的正确方法是什么,以便在宏完成后这就是您正在查看的工作簿。

Should I use any Windows()based code or is this related to .setfocus? I am just guessing.

我应该使用任何Windows()基于代码的代码还是与此相关.setfocus?我只是猜测。

回答by MikeD

Workbookon its own may not be qualifying enough, depending what you actually see on your screen at runtime. If the VBA runs within the same workbook, try

Workbook本身可能不够合格,这取决于您在运行时实际在屏幕上看到的内容。如果 VBA 在同一个工作簿中运行,请尝试

ThisWorkbook.Activate.

ThisWorkbook.Activate.

If your code is in workbook WB2 but processing another workbook WB1, you may want to call your VBA with that workbook as parameter and make it active at the end of your code.

如果您的代码在工作簿 WB2 中,但正在处理另一个工作簿 WB1,则您可能希望使用该工作簿作为参数调用 VBA,并在代码末尾使其处于活动状态。

So the example VBA code is in WB2 ...

所以示例 VBA 代码在 WB2 ...

Sub CallStuff()
    Debug.Print "Hey, I am " & ThisWorkbook.Name
    Debug.Print "starting to work on " & Application.Workbooks("Book1").Name

    DoStuff Application.Workbooks("Book1")

End Sub

Sub DoStuff(WB As Workbook)

    WB.Worksheets("Sheet1").[A1] = "Co-cooo!"
    'do other stuff on WB
    WB.Activate
End Sub

situation before start of VBA ... WB2 active and executing code step 1

VBA 启动前的情况... WB2 激活并执行代码 第1步

after 2 lines of code WB2 still active, preparing subroutine with parameter step 2

2 行代码后 WB2 仍处于活动状态,准备带参数的子程序 第2步

processed WB1, but WB2 still active step 3

已处理 WB1,但 WB2 仍处于活动状态 第 3 步

now making WB1 active step 4

现在使 WB1 处于活动状态 第四步