简体   繁体   中英

Don't execute Worksheet_Calculate event on Workbook_Open

I have an excel workbook.

In one of the worksheets I make use of the Worksheet_Calculate event. This works fine. However when the workbook is first opened I do not want MyFunction to be called. What is the best away to do this?

My only idea so far is the following (I don't like this though). On the workbook open method put a time stamp in one of the worksheets and then have an if statement in my worksheet_calculate and if the current time is 1 minute past the time stamp (that was created on the workbook_open event) run the code otherwise don't.

Thinking there must be a better way though?

Private Sub Worksheet_Calculate()
    MyFunction()
End Sub

Update

The reason I do not want my code to execute when the workbook opens is because there are some Bloomberg formulas that take a little time to execute so initially some of the cell values are #NA.

This causes a type mismatch error - any errors that happen are logged and an e-mail is automatically sent. So every time the workbook is opened there is an 'error' as the bloomberg formulas have not updated straight away

The code below should work for you. The first time calculate is called it sets the flag to allow future calls to process. This means the first call to calculate does not process your code.

ThisWorkbook Code:

Private Sub Workbook_Open()
    bFunctionFlag = False
End Sub

Sheet Code:

Public bFunctionFlag As Boolean

Private Sub Worksheet_Calculate()
    If bFunctionFlag = True Then Call MyFunction
    bFunctionFlag = True
End Sub

Private Function MyFunction()
    MsgBox "Calculate"
End Function

In the workbook open event you can have

Private Sub Workbook_Open()
    Application.EnableEvents = False
    'Run Workbook Open code
    Application.EnableEvents = True
End Sub

or if you need events to run from external services then do something similar with a public variable. Eg Dim wbOpenEventEnded as Boolean

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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