excelvbaexcel-formula

Event change calculation formula


I have a formula in Sheet1 in J4 that looks at a timer in F4 that counts down. Once it hits 00:00:04 it then adds a 1 to J4 as:

IF(F4="00:00:04", "1", "0")

In Sheet1's code I then have this VBA that looks at the value in J4:

Private Sub Worksheet_Calculate()

Static MyOldVal

If Range("J4").Value <> MyOldVal Then

    Call Clear
    MyOldVal = Range("J4").Value

End If

End Sub

And if it has changed to 1 it then initiats the "Clear" macro which has this code (and works absolutely fine):

Sub Clear()

If Worksheets("Sheet1").Range("J4").Value = 1 Then

Worksheets("Sheet1").Range("J1").ClearContents

End If

End Sub

I then have a similar thing with the countdown in J5 for 2 seconds later:

IF(F4="00:00:02", "1", "0")

In Sheet1's code I then have this VBA that looks at the count in J5:

Private Sub Worksheet_Calculate()

Static MyOldVal2

If Range("J5").Value <> MyOldVal2 Then

    Call AddStake
    Call AddPlacedFormula
    MyOldVal2 = Range("J5").Value

End If

End Sub

And if it has changed to 1 it then initiats the "AddStake" and "AddPlacedFormula" macros.

The "AddStake" macro code is:

Sub AddStake()

If Worksheets("Sheet1").Range("J5").Value = 1 Then

    Dim WS As Worksheet

    Set WS = Worksheets("Sheet1")

    WS.Range("N9").Value = "10"

End If

End Sub

Which works fine and does as it is supposed to.

The issue is with the "AddPlacedFormula" macro which has code:

Sub AddPlacedFormula()

If Worksheets("Sheet1").Range("J5").Value = 1 Then

    Dim WS As Worksheet

    Set WS = Worksheets("Sheet1")

    WS.Range("J1").Value = "=COUNTIF(O9:O67, ""Placed"")"
    
End If

End Sub

The line it is falling down on is:

WS.Range("J1").Value = "=COUNTIF(O9:O67, ""Placed"")"

This is not just for this formula and doesn't work with any other formulae I add in the same place but does work if I add a value similar to the "AddStake" macro. This is the error and the debug:

This is the error

This is the Debug

I have also tried using the R1C1 values instead and this doesn't work either:

WS.Range("J1").FormulaR1C1 = "=COUNTIF(R[8]C[5]:R[66]C[5], ""Placed"")"

Solution

  • Instead of

    try using

    Additionaly it might be a good idea to switch off Events when this macro is triggered:

    Sub AddPlacedFormula()
    
        Dim WS As Worksheet
        Set WS = Worksheets("Sheet1")
    
        If WS.Range("J5").Value = 1 Then
            Application.EnableEvents = False
    
            WS.Range("J1").Formula = "=COUNTIF(O9:O67, ""Placed"")"
    
            Application.EnableEvents = True
        End If
    
    End Sub