VBA 事件:在使用 workbook_open 运行代码之前加载工作簿
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3957758/
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
VBA Events: load workbook before running code using workbook_open
提问by samcooper11
I want to run a VBA macro AFTER the workbook has finished opening. I tried to use workbook_open but this runs before the workbook has finished opening. This doesn't work for me as I need to loop through each sheet like so...
我想在工作簿打开后运行 VBA 宏。我尝试使用 workbook_open 但这在工作簿完成打开之前运行。这对我不起作用,因为我需要像这样循环遍历每张纸......
Private Sub Workbook_Open()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
'do stuff on each sheet
Next ws
End Sub
Does anyone know if there is an event which runs once the workbook has finished opening? Or have any other suggestions on how I can achieve this?
有谁知道工作簿完成打开后是否会运行一个事件?或者对我如何实现这一目标有任何其他建议?
回答by Robert
I had a similar problem that I solved using Application.OnTime.
我有一个类似的问题,我使用Application.OnTime解决了这个问题。
From the linked MSDN Library Article:
来自链接的 MSDN 库文章:
Schedules a procedure to be run at a specified time in the future (either at a specific time of day or after a specific amount of time has passed).
安排要在将来的指定时间运行的过程(在一天中的特定时间或经过特定时间后)。
You could try using this method to provide the workbook with enough time to open before running the DoStuffprocedure:
您可以尝试使用此方法在运行该DoStuff过程之前为工作簿提供足够的打开时间:
Private Sub Workbook_Open()
Application.OnTime Now + TimeValue("00:00:01"), "DoStuff"
End Sub
Ensure the DoStuffprocedure is not in a worksheet module:
确保该DoStuff过程不在工作表模块中:
Private Sub DoStuff()
'Implementation...
End Sub
The time can be adjusted but one second was satisfactory for me.
时间可以调整,但一秒钟对我来说很满意。
回答by Michael
Put your code in the Workbook_Activate event. It happens after the Open event.
将您的代码放在 Workbook_Activate 事件中。它发生在 Open 事件之后。
Private Sub Workbook_Activate()
' Code goes here
End Sub
回答by Charles Williams
Try using ThisWorkbook rather than ActiveWorkbook:
尝试使用 ThisWorkbook 而不是 ActiveWorkbook:
Private Sub Workbook_Open()
Dim osht As Worksheet
For Each osht In ThisWorkbook.Worksheets
Debug.Print osht.Name
Next osht
End Sub

