Home > Blockchain >  How to avoid show MsgBox if no difference found when compare Rng1 to Rng2?
How to avoid show MsgBox if no difference found when compare Rng1 to Rng2?

Time:12-26

I am using below code to compare rng1 to rng2 and show all differences in MsgBox. The code works, but I need to avoid showing a message box if no difference was found. As always, your help is much appreciated.

Option Explicit

Sub Test_Copied_Data2()

   Dim Sh1 As Worksheet: Set Sh1 = Sheets("Auto")
   Dim Sh2 As Worksheet: Set Sh2 = Sheets("Closed_Items")
   
   Dim rng1 As Range, rng2 As Range, A As Range, LastRow As Long

    Set rng1 = Sh1.Range("A2:A22")
    
    Dim Count_rng1 As Long
     Count_rng1 = WorksheetFunction.CountA(rng1)
    
    If Count_rng1 = 0 Then Exit Sub
    
    LastRow = Sh2.Cells(Rows.Count, "B").End(xlUp).Row
     Set rng2 = Sh2.Range("B" & Count_rng1 & ":" & "B" & LastRow)
  
  Dim Msg As String
   Msg = "These Item not found in sheet 'Closed_Items' : " & vbNewLine
      
  For Each A In rng1
    If Len(A.value) > 0 And Application.CountIf(rng2, A.value) = 0 Then
        Msg = Msg & A.value & vbNewLine
     End If
    Next
  Msg = Left(Msg, Len(Msg) - 2)
 MsgBox Msg
                                                                        
End Sub

CodePudding user response:

    Dim msg As String
    For Each A In rng1
        If Len(A.Value) > 0 And Application.CountIf(rng2, A.Value) = 0 Then
            msg = msg & vbLf & A.Value
        End If
    Next
    
    If Len(msg) > 0 Then
        MsgBox "These Item not found in sheet 'Closed_Items' : " & msg, vbExclamation
    Else
        'MsgBox "OK", vbInformation
    End If
  • Related