简体   繁体   English

从 Workbook_Open() 运行时,Workbooks.Add 不会激活新工作簿

[英]Workbooks.Add doesn't activate the new workbook when running from Workbook_Open()

I'm trying to run a macro when my workbook is opened.我正在尝试在打开工作簿时运行宏。 The macro is supposed to create a new workbook using Workbooks.Add and end with the new workbook active.该宏应该使用Workbooks.Add创建一个新工作Workbooks.Add并以新工作簿活动结束。 However, I cannot seem to make this happen no matter what I try.但是,无论我尝试什么,我似乎都无法做到这一点。

The simplest attempts I tried were the following (you can try it yourself):我尝试过的最简单的尝试如下(您可以自己尝试):

Private Sub Workbook_Open()
    Dim wb As Workbook
    Set wb = Workbooks.Add
    wb.Activate
End Sub

Or this one from within the module itself:或者来自模块本身的这个:

Sub Auto_Open()
    Dim wb As Workbook
    Set wb = Workbooks.Add
    wb.Activate
End Sub

I tried various things such as adding the following lines of code:我尝试了各种方法,例如添加以下代码行:

DoEvents or DoEvents

Application.Wait (Now + TimeValue("00:00:02"))

I also tried using If Then statements to check the name of the active workbook, but that didn't work either.我还尝试使用If Then语句来检查活动工作簿的名称,但这也不起作用。

In the end, the original file that I clicked on is still the active workbook.最后,我点击的原始文件仍然是活动工作簿。 How can I get the newly created workbook to be the active window when the macro is finished running?宏完成运行后,如何使新创建的工作簿成为活动窗口? Thanks!谢谢!

Edit: By the way, note that if you try running the exact same code in a regular sub, it behaves the way that I want.编辑:顺便说一句,请注意,如果您尝试在常规子程序中运行完全相同的代码,它会按照我想要的方式运行。 It just doesn't seem to work when running in the 'run on workbook open' subs.在“在工作簿打开时运行”子程序中运行时,它似乎不起作用。

Application.Wait just idles the Excel Application, so that won't work as you've observed. Application.Wait只是使 Excel 应用程序处于空闲状态,因此不会像您所观察到的那样工作。 If all else fails (I'm not in a position to test at the moment) you could use Application.OnTime to schedule a procedure that creates a new workbook and activates it, 1 second after the Workbook_Open event:如果所有其他方法都失败(我目前无法进行测试),您可以使用Application.OnTime来安排一个过程,在Workbook_Open事件1 秒创建一个新工作簿并激活它:

Option Explicit

Private Sub Workbook_Open()
Application.OnTime Now + TimeValue("00:00:01"), "addNewWb"
End Sub

Private Sub addNewWb()
Dim wb As Workbook
Set wb = Workbooks.Add
wb.Activate
End Sub

I have been running all the different ways I can.我一直在尝试各种不同的方式。 But a workaround is to add a MsgBox但解决方法是添加一个MsgBox

Private Sub Workbook_Open()

        Dim wb As Workbook
        Set wb = Workbooks.Add
        wb.Activate

        MsgBox "New Book Added"

End Sub

When you will click okay on the MsgBox, it will stay on the Newly created Workbook.当您在 MsgBox 上单击确定时,它将保留在新创建的工作簿上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM