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

时间:2017-10-12 09:04:20

标签: excel vba excel-vba

我有两个数据列表。 第一个列表是包含所有新数据的列表,在第二个列表中我有旧数据。现在我希望Excel显示一个消息框,告诉我第二个列表中缺少哪些数据。

使用在其他主题中找到的信息,我能够将这两个列表相互比较,并在第三张表格中输出这些数据。 但是我真的不需要第三张,但我希望在消息框中有这些差异.. :)任何人都可以帮助我如何正确地更改此代码?

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">

<stroke android:color="#0a0909"
    android:width="2dp"/>

<corners android:radius="20dp"/>

<gradient android:angle="45"
    android:type="linear"
    android:startColor="#d61a1a"
    android:endColor="#19f269"
    android:useLevel="false"/>

<size android:height="250dp"
    android:width="250dp"/>
</shape>

2 个答案:

答案 0 :(得分:1)

未经测试 - 直接在SO中输入,但应显示方式:(在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

答案 1 :(得分:0)

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

每当比较两个列表时,我会使用某种Collection或Dictionary。

我的方法是将第二个列表中的所有值添加到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
相关问题