Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

populate message box based on comparing two values

0

Hi

I try to pops message box when write the value in column D for adjacant cell in column B contains DISCOUNT word , if the value is bigger than value is existed under NET TOTAL  then should pops message box  and clear value in column D for adjacant cell in column B contains DISCOUNT word.

I try writing this code , but I failed .

Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Range("D:D"), Target) Is Nothing Then
Dim rngA As Range
Dim cell As Range
rngA = Sheets("Jan BY").Range("B2:B" & lr - 2)
For Each cell In rngA
If cell.Value = "NET TOTAL" And Target.Value > cell.Value Then
MsgBox ("EXCEEDS NUMBER !"), vbCritical
Target.Value = ""
End If
Next cell
End If
End Sub
Answer
Discuss

Answers

0
Selected Answer

Hello Omaran,

If I understand correctly what you are trying to do, using your uploaded file for reference, this is what I get.

Compare "D7" value to "B9" value; compare "D17" value to "B19" value; and "D25" value to "B27" value. To do this I have modified your code in the following ways:

Added a check at the start to make sure only one cell is selected

Gave (Set) a value to rngA and removed the "-2" for the lr value.

Declared variable "lr" and gave it a value.

Modified the "If" statement to compare the value entered in column "D" opposite "DISCOUNT" to the value below "NET TOTAL" in column "B"

The revised macro is:

Private Sub Worksheet_Change(ByVal Target As Range)

' check if multple cells are selected
If Target.Count > 1 Then Exit Sub

Dim rngA As Range
Dim cell As Range
Dim lr As Long

lr = Cells(Rows.Count, 2).End(xlUp).Row
Set rngA = Sheets("Jan BY").Range("B1:B" & lr)

' check if selected cell is in column "D"
If ActiveCell.Column <> 4 Then Exit Sub
If Not Intersect(ActiveCell, Range("D1:D" & lr)) Is Nothing Then

For Each cell In rngA
    If cell.Value = "NET TOTAL" Then
        ' compare value in column "D" to the value below "NET TOTAL"
        If cell.Offset(-1, 2).Value > cell.Offset(1).Value Then
        MSGBOX ("EXCEEDS NUMBER !"), vbCritical
        Target.Value = ""   ' delete the value in column "D"
        End If
    End If
Next
End If

End Sub
'

If this is what you are trying to do please mark my answer as Selected.

Cheers    :-)

Discuss

Discussion

perfect !
many thanks , buddy!
have a nice weekend
Omaran (rep: 8) Feb 17, '24 at 1:25 pm

Glad I was able to help.
Thanks for selecting my answer.
WillieD24 (rep: 557) Feb 17, '24 at 5:29 pm
Add to Discussion


Answer the Question

You must create an account to use the forum. Create an Account or Login