vba Worksheet_Activate 在工作簿打开时不触发

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

Worksheet_Activate not triggering when workbook opened

excelvbaeventsactivation

提问by jaegee

Two days ago my code to populate ActiveX combo boxes in my Excel sheets stopped functioning when I open the document. I have since discovered that the Worksheet_Activate() no longer triggers when I open sheets.

两天前,当我打开文档时,用于填充 Excel 工作表中的 ActiveX 组合框的代码停止运行。我后来发现 Worksheet_Activate() 在我打开工作表时不再触发。

Now even if I create a simple workbook with only the following code in Sheet 1, it doesn't trigger when I open the workbook.

现在,即使我在 Sheet 1 中创建了一个仅包含以下代码的简单工作簿,它也不会在我打开工作簿时触发。

Private Sub Worksheet_Activate()
   MsgBox ("Worksheet has been activated")
End Sub

However, if I click on another tab and click back to the sheet containing the code, it does trigger.

但是,如果我单击另一个选项卡并单击返回包含代码的工作表,它会触发。

I have tried playing with adding Application.EnableEvents = True and Worksheets("Sheet1").Activate to the Workbook_Open (which does trigger) but still no luck.

我试过添加 Application.EnableEvents = True 和 Worksheets("Sheet1").Activate 到 Workbook_Open (触发),但仍然没有运气。

We're running Excel 2010 and the same problem is occurring on my colleagues' machines as well. Any ideas?

我们正在运行 Excel 2010,我同事的机器上也出现了同样的问题。有任何想法吗?

采纳答案by Mr. Mascaro

In your Workbook_Openevent turn off ScreenUpdating, activate a different sheet, activate the sheet you want the event to fire, turn ScreenUpdatingback on.

在您的Workbook_Open事件关闭中ScreenUpdating,激活不同的工作表,激活您希望事件触发的工作表,然后ScreenUpdating重新打开。

回答by Wim

I know this is an older question, but there is no need to first activate another worksheet and then re-activate the one you want:

我知道这是一个较旧的问题,但没有必要先激活另一个工作表,然后重新激活你想要的:

Private Sub Workbook_Open()
    ' Bug in Excel:
    ' The Worksheet_Activate event does not fire for the sheet that is active
    ' when the workbook is opened, so call it explicitely. Make sure that
    ' Worksheet_Activate() is declared as Public.
    ' Ignore ActiveSheets without (Public) Worksheet_Activate()
    On Error Resume Next
    Call ActiveSheet.Worksheet_Activate
    On Error GoTo 0
End Sub

It's also not good practice to reference a worksheet by Namelike in Worksheets("Sheet1"), unless you have a very good reason to do so. Better is to use the CodeName. For details, see this post.

像 in 那样通过Name引用工作表也不是一个好习惯Worksheets("Sheet1"),除非您有充分的理由这样做。更好的是使用CodeName。有关详细信息,请参阅此帖子