vba OnOpenExcelWorksheet 事件在工作表打开时触发?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2998403/
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
OnOpenExcelWorksheet Event To Trigger When Worksheet Opens?
提问by sooprise
How can I run code when a Worksheet opens? (The code that I want to run is contained in the opening worksheet)
工作表打开时如何运行代码?(我要运行的代码包含在打开的工作表中)
回答by Tommy
You can put certain code in the Worksheet_Activate() function which will run when the sheet is selected. Additionally, use the Worksheet_Deactivate() to run code when you leave the wokrsheet and go to another one. These functions go in the worksheet object code.
您可以将某些代码放入 Worksheet_Activate() 函数中,该函数将在选择工作表时运行。此外,当您离开 wokrsheet 并转到另一个 wokrsheet 时,请使用 Worksheet_Deactivate() 来运行代码。这些函数位于工作表目标代码中。
Private Sub Worksheet_Activate()
MsgBox ("Hi")
End Sub
Private Sub Worksheet_Deactivate()
MsgBox ("Bye")
End Sub
回答by Ben McCormack
I'm not sure how to get code to run when a worksheetopens, but you can get it to run when a workbookopens.
我不确定如何在工作表打开时运行代码,但您可以在工作簿打开时运行代码。
In the VBA editor, open the Microsoft Excel Object called "ThisWorkbook." At the top of the editor window, you should see two drop-down boxes: (General) and (Declarations). Change the (General) combo box to be "Workbook."
在 VBA 编辑器中,打开名为“ThisWorkbook”的 Microsoft Excel 对象。在编辑器窗口的顶部,您应该会看到两个下拉框:(General) 和 (Declarations)。将(常规)组合框更改为“工作簿”。
This will give you method called Workbook_Open(). Code placed in this method will execute when you open the Excel Workbook.
这将为您提供称为Workbook_Open(). 当您打开 Excel 工作簿时,将执行放置在此方法中的代码。
Furthermore, you have more events at your disposable, available in the (Declarations) section when you have Workbook selected, such as SheetActivateand SheetChanged, among others. I haven't used those methods, but they may be something to try if you need events related to individual worksheets and not just the entire workbook.
此外,当您选择了工作簿时,您可以在(声明)部分中获得更多事件,例如SheetActivate和SheetChanged等。我没有使用过这些方法,但是如果您需要与单个工作表相关的事件而不仅仅是整个工作簿,它们可能是可以尝试的。

