I am struggling with a problem with Worksheet_Calculate(). As suggested here Run Sub procedure with IF() statement in cell I have tried to translate an excel IF() statement in to VBA in the Worksheet_Calculate() as the cells will be activated with dynamic formula. However, when the specific formula in VBA meets the condition the code that is meant to run crashes excel. If I run the code in the VBE as a separate sub it runs perfectly and executes correctly as what is needed. Below is the code, any help is greatly appreciated.
Private Sub Worksheet_Calculate()
Dim rng As Range
Dim mainSheet As Worksheet
Set mainSheet = Worksheets("Sheet1")
If (mainSheet.Range("D2").Value = "ABOVE" And mainSheet.Range("F2").Value > mainSheet.Range("E2").Value And mainSheet.Range("H2").Value = "YES" And mainSheet.Range("I2").Value = "1") Or (mainSheet.Range("D2").Value = "BELOW" And mainSheet.Range("F2").Value < mainSheet.Range("E2").Value And mainSheet.Range("H2").Value = "YES" And mainSheet.Range("I2").Value = "1") Then
'Disable events so as not to overload the worksheet calculate - as the worksheet is calculating dont change/ delete
Application.EnableEvents = False
'enter and copy data
Set rng = Sheets("Sheet3").Range("A:A").End(xlDown)
rng.Offset(1, 0) = Format(Now(), "dd/mm/yyyy")
rng.Offset(1, 1) = Format(Now(), "ddd")
rng.Offset(1, 2) = Format(Now(), "hh:nn")
rng.Offset(1, 3) = Sheets("Sheet1").Range("C2")
rng.Offset(1, 4) = Sheets("Sheet1").Range("A2")
rng.Offset(1, 5) = Sheets("Sheet1").Range("E2")
'delete row information
Worksheets("Sheet1").Range("A2").ClearContents
Worksheets("Sheet1").Range("C2:E2").ClearContents
Worksheets("Sheet1").Range("G2:H2").ClearContents
're-sort colums
Application.Run "SortByMarket"
Application.ScreenUpdating = True
'turn back on events
Application.EnableEvents = True
End If
Also, this is obviously not the most efficient way possible to code this so any input/ advice is welcome.