简体   繁体   中英

Message Box if cell exceeds another cell

What would be the best way to write a VBA code to have a message box pop up if the value in one cell is less than or greater than another cell - and then display the difference?

Column N contains total appts (manual input)

Column R contains total results (formula generated)

If the cell in column R after calculated is less than or greater than the cell in column N the message box would pop up and say Total results is less than appts by # or Total results is greater than appts by #.

Add the following routine to your required sheet in the VBA project (eg Sheet1)

Private Sub Worksheet_Change(ByVal Target As Range)

    If Target = Range("N1") Or Target = Range("R1") Then 'Only attempt to run the below code if target is a range you care about

        If Range("R1").Value2 <> Range("N1").Value2 Then
            MsgBox "Values differ"
        End If

    End If

End Sub

On the assumption that you want to compare two cells with one another (as opposed to a whole column of cells):

Private Sub Worksheet_Change(ByVal Target As Range)

    If Range("N1") > Range("R1") Then
        MsgBox "Oops. Results less than Input by " & Abs(Range("N1") - Range("R1"))
    End If

    If Range("N1") < Range("R1") Then
        MsgBox "Oops. Results greater than Input by " & Abs(Range("N1") - Range("R1"))
    End If

End Sub

That should achieve the following:

  • Compare two cells with one another whenever the sheet changes (regardless whether it be the formula generated value for R1, the manual input for N1, or anything else on the sheet)
  • Identify which is greater
  • Pop up an appropriate message

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