开发者

Behaviour of Worksheet_Calculate event in Excel – stored events?

and thank you for reading my post. I have encountered a strange (in my opinion) behaviour of Worksheet_Calculate event in Excel (Windows 7 Ultimate, Excel 2010), let me describe the problem I’m having by giving you a set up.

Take a Workbook with 2 Sheets. Sheet 2 Cell A1 has a formula =Sheet1!A1, EnableCalculation property of Sheet2 is set to TRUE and in Sheet2 Object there is a Sub

Private Sub Worksheet_Calculate()
    i = MsgBox("Value " & Me.Range("A1").Value, vbOKOnly)
End Sub

In Module1 there is a SUB

Public Sub mySub()
    Application.EnableEvents = False
    ThisWorkbook.Worksheets(2).EnableCalculation = True
    ThisWorkbook.Worksheets(2).EnableCalculation = False
    Application.EnableEvents = True
End Sub

Now, enter 1 in Sheet1 Cell A1 – a message box with “Value 1” is displayed. Next, set Enabl开发者_高级运维eCalculation property of Sheet2 to FALSE and enter 2 in Sheet1 Cell A1 – nothing happens. Now, run the mySub in Module 1 – Cell A1 on Sheet2 displays 2 and EnableCalculation property of Sheet2 is set to FALSE. So far, so good. Now enter 3 in Sheet1 Cell A1 – a message box with “Value 2” is displayed!

It would seem that during the execution of mySub a Calculation event was fired (even though Application.EnableEvents was set to FALSE) and the value of 2 was stored (where?) and then this event was released when 3 was entered into Cell A1 on Sheet1 (even though EnableCalculation is set to FALSE for Sheet2). Any clue what’s going on here and how to “fix” this strange behaviour?

Many thanks.


Quote from http://www.decisionmodels.com

'Setting enablecalculation to false and then back to true will flag all the formulae on the worksheet as uncalculated. If the calculation mode is Automatic a recalculation will be triggered. All calculation methods, including Sheet.Calculate but excluding Range.Calculate, will then calculate all the formulae on the sheet. You can use this method as a way of simulating Calculatefull at worksheet rather than workbook level. Note that Sheet.Calculate will not reset the uncalculated formulae flags, so two Sheet.Calculates in succession after toggling the EnableCalculation property will both do a Full Sheet Calculate.'

This seems to fix it

Public Sub mySub()
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual
    ThisWorkbook.Worksheets(2).EnableCalculation = True
    ThisWorkbook.Worksheets(2).EnableCalculation = False
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True
End Sub
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜