Is there a vba code which opens a msgbox when cell value is not equal to a specific cell?

62 Views Asked by At

I'm new to using vba so I wanted to know if there's a way I can get excel to show a message box when the value of a cell is not equal to another cell in my worksheet?

I saw this code being used for when the cell is not equal to a specific value: Is there a vba code which opens a msgbox when cell value is not equal to "X"?

type herPrivate Sub Worksheet_Change(ByVal Target As Range)
    Dim myCell As Range

    For Each myCell In Range("G4:G160")

        If (Not IsEmpty(myCell)) And myCell.Value <> 17521 And myCell.Value <> "" Then

            MsgBox "INCORRECT SKU RECHECK PALLET AND INFORM SUPERVISOR", vbCritical

            Exit Sub
        End If

    Next myCell
End Sube

Thanks in advance for your help

2

There are 2 best solutions below

0
Gustav On

It could something like this - a lookup function:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim Cell    As Excel.Range

    If Not IsEmpty(Target) Then
        For Each Cell In Range("G4:G160")
            If Not IsEmpty(Cell) Then
                If Cell = Target Then
                    Exit For
                End If
            End If
        Next
    End If
    
    If Cell Is Nothing Then
        MsgBox "INCORRECT SKU RECHECK PALLET AND INFORM SUPERVISOR", vbCritical
    Else
        Set Cell = Nothing
    End If
    
End Sub
1
VBasic2008 On

A Worksheet Calculate: Two Cells Contain Different Numbers

  • This code runs on each calculation of the worksheet's formulas.
  • Both cells contain formulas and if any of their results is not a number, a message is displayed.
  • If they both contain numbers and they are not equal, a different (the 'required') message is displayed.

Sheet Module e.g. Sheet1 (Not Standard Module e.g. Module1 or Thisworkbook Module)

Private Sub Worksheet_Calculate()
    
    Const Cell1 As String = "A1"
    Const Cell2 As String = "A2"
    
    Dim Val1 As Variant, Val2 As Variant
    
    With Me ' reference the worksheet in a sheet module
        Val1 = .Range(Cell1).Value
        Val2 = .Range(Cell2).Value
    End With
    
    If VarType(Val1) <> vbDouble Then
        MsgBox "The calculated value in cell """ & Cell1 _
            & """ is not a number.", vbExclamation
        Exit Sub ' the 1st value is not a number (not caring about 'Val2')
    End If
    
    If VarType(Val2) <> vbDouble Then
        MsgBox "The calculated value in cell """ & Cell2 _
            & """ is not a number.", vbExclamation
        Exit Sub ' the 2nd value is not a number (when 'Val1' is a number)
    End If
    
    If Val1 = Val2 Then Exit Sub ' the numbers are equal
    
    MsgBox "The calculated values " & Val1 & " in cell """ & Cell1 & """ and " _
        & Val2 & " in cell """ & Cell2 & """ are not equal!", vbExclamation
    
End Sub