简体   繁体   中英

VBA code to show message box popup if the formula in the target column exceeds a certain value

I found this code on this site for a particular cell

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

But I was wondering if it is possible to make this work for an entire column rather than one particular cell?

Try this for your event code:

Private Sub Worksheet_Calculate()
    Dim rr As Range, r As Range
    Set rr = Range("A:A").Cells.SpecialCells(xlCellTypeFormulas)
    For Each r In rr
        If r.Value > 0.5 Then
            MsgBox "Discount too high"
        End If
    Next r
End Sub

EDIT#1:

if you want to restrict the message to a single row, then remove the first sub and replace it with:

Private Sub Worksheet_Change(ByVal Target As Range)
    rt = Target.Row
    If Range("A" & rt) > 0.5 Then
        MsgBox "Discount too high"
    End If
End Sub

I would say this is the wrong way of doing thing in Excel :).

Can I suggest the following: 1. Add Conditional Formatting to cells depending on the values eg > 0.5 2. Add in the cell next to this cell a simple IF formula that signal the error.

Using events will suppress undo operations

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