比较VBA中的列表和Msgbox中的输出差异

我有两个数据列表。 第一个列表是所有新数据的列表,而第二个列表是旧数据。 现在我想让Excel展示一个消息框,告诉我在第二个列表中缺less哪些数据。

使用其他主题中find的信息,我已经能够将这两个列表相互比较,并在第三个表中输出这些数据。 不过,我并不需要第三张纸,但我想在消息框中有这些差异。:)任何人都可以帮我了解如何正确更改此代码?

Sub Compare() Dim sh1 As Worksheet, sh2 As Worksheet, sh3 As Worksheet, lr1 As Long, lr2 As Long, rng1 As Range, rng2 As Range, c As Range Set sh1 = Sheets(1) Set sh2 = Sheets(2) Set sh3 = Sheets(3) lr1 = sh1.Cells(Rows.Count, 1).End(xlUp).Row lr2 = sh2.Cells(Rows.Count, 1).End(xlUp).Row Set rng1 = sh1.Range("A2:A" & lr1) Set rng2 = sh2.Range("A2:A" & lr2) With sh3 'If header not there, put them in If .Range("a1") = "" Then .Range("a1") = "Extras in List 2" End If End With For Each c In rng2 If Application.CountIf(rng1, c.Value) = 0 Then sh3.Cells(Rows.Count, 1).End(xlUp)(2) = c.Value End If Next End Sub 

非testing – 直接在SO中input,但应该显示方式:(在End With之后开始)

 dim msg as string msg = "Extras: " For Each c In rng2 'edit: skip empty cells If len(c.Value) > 0 And Application.CountIf(rng1, c.Value) = 0 Then 'sh3.Cells(Rows.Count, 2).End(xlUp)(2) = c.Value msg = msg & c.value & ", " End If Next msg = left(msg,len(msg)-2) msgbox msg 

@PatrickHonorez有更好的答案,因为他纠正了OP的代码。

每当比较两个列表,我使用某种集合或字典。

我的做法是将第二个列表中的所有值添加到ArrayList中,然后从ArrayList中删除第一个列表值。 这样,只有新的值保留在ArrayList中。

 Sub Compare() Dim cell As Range, list As Object Set list = CreateObject("System.Collections.ArrayList") With Worksheets(2) For Each cell In .Range("A2", .Range("A" & .Rows.Count).End(xlUp)) If cell.Value <> "" Then If Not list.Contains(cell.Value) Then list.Add cell.Value End If Next End With With Worksheets(1) For Each cell In .Range("A2", .Range("A" & .Rows.Count).End(xlUp)) If list.Contains(cell.Value) Then list.Remove cell.Value Next End With With Worksheets(3) .Columns(1).ClearContents .Range("A1") = "Extras in List 2" If list.Count = 0 Then MsgBox "No new data", vbInformation, "" Else MsgBox Join(list.ToArray, ", "), vbInformation, "New Data" .Range("A2").Resize(list.Count).Value = Application.Transpose(list.ToArray) End If End With End Sub