VBA code to show Message Box popup if the formula in the target cell exceeds a certain value VBA code to show Message Box popup if the formula in the target cell exceeds a certain value vba vba

VBA code to show Message Box popup if the formula in the target cell exceeds a certain value


You could add the following VBA code to your sheet:

Private Sub Worksheet_Change(ByVal Target As Range)    If Range("A1") > 0.5 Then        MsgBox "Discount too high"    End IfEnd Sub

Every time a cell is changed on the sheet, it will check the value of cell A1.

Notes:

  • if A1 also depends on data located in other spreadsheets, the macro will not be called if you change that data.
  • the macro will be called will be called every time something changes on your sheet. If it has lots of formula (as in 1000s) it could be slow.

Widor uses a different approach (Worksheet_Calculate instead of Worksheet_Change):

  • Pros: his method will work if A1's value is linked to cells located in other sheets.
  • Cons: if you have many links on your sheet that reference other sheets, his method will run a bit slower.

Conclusion: use Worksheet_Change if A1 only depends on data located on the same sheet, use Worksheet_Calculate if not.


Essentially you want to add code to the Calculate event of the relevant Worksheet.

In the Project window of the VBA editor, double-click the sheet you want to add code to and from the drop-downs at the top of the editor window, choose 'Worksheet' and 'Calculate' on the left and right respectively.

Alternatively, copy the code below into the editor of the sheet you want to use:

Private Sub Worksheet_Calculate()If Sheets("MySheet").Range("A1").Value > 0.5 Then    MsgBox "Over 50%!", vbOKOnlyEnd IfEnd Sub

This way, every time the worksheet recalculates it will check to see if the value is > 0.5 or 50%.


I don't think a message box is the best way to go with this as you would need the VB code running in a loop to check the cell contents, or unless you plan to run the macro manually. In this case I think it would be better to add conditional formatting to the cell to change the background to red (for example) if the value exceeds the upper limit.