Search code examples
excelvba

Is there a way to have a macro run automatically IF a cell changes to a certain value (i.e. if greater than X)?


I'm creating a calculator and have to compare dates as part of the tool. I'm trying to get the macro to run automatically AND check if the days between the dates is greater than 185 days. When researching and testing out different options, I haven't been successful. It can run if I create a button but need it to run automatically (if days between dates are greater than 185 days). Cell C10 is the cell that calculates the number of days between the two dates the user provides.

This is my original code, but changed it so that it would be more automatic:

Sub Duration_Error()
  
  If Range("C10") > 185 Then
    MsgBox "Based on the dates provided, this greater than 185 days .Please contact XYZ.", vbRetryCancel + vbExclamation, Title:="Duration Error"
Else
    Exit Sub

End If
    
End Sub

The below is what I tried but when I test it with the dates, nothing happens. When I try running it from VBA I know get the Macros dialog box to appear - so I know I'm doing something very wrong.

Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Address = "$C$10" And "$C$10" > 185 Then
  MsgBox "Based on the dates provided, this greater than 185 days .Please contact XYZ.", vbRetryCancel + vbExclamation, Title:="Duration Error"
Else
    Exit Sub

End If
    
End Sub

Solution

  • A Worksheet Change: Sum of Two Cells Override

    • It is assumed that cells C8 and C9 are manually populated.
    • In C10 is a formula that uses these two cells to return a numeric value.
    • Show a message if the value in C10 is greater than 185.
    Private Sub Worksheet_Change(ByVal Target As Range)
        
        Const MSG_PROMPT As String = "Based on the dates provided, " _
            & "the difference is greater than 185 days. Please contact XYZ."
        Const MSG_TITLE As String = "Duration Error"
        Const TRIGGER_RANGE As String = "C8,C9" ' adjust!
        Const CHECK_CELL As String = "C10"
        Const MAX_DAYS As Long = 185
        
        If Intersect(Me.Range(TRIGGER_RANGE), Target) Is Nothing Then Exit Sub
        
        With Me.Range(CHECK_CELL)
            If Not IsNumeric(.Value) Then Exit Sub
            If .Value <= MAX_DAYS Then Exit Sub
        End With
        
        MsgBox MSG_PROMPT, vbExclamation, MSG_TITLE
        
    End Sub