在Do循环中查找功能,提供不一致的结果

时间:2015-12-08 15:02:47

标签: excel vba excel-vba

我正在尝试测试两个列表之间的差异。我的VBA代码应该遍历列表一并使用find方法查看列表二中的每个项目。如果在列表2中找不到该项,我使用复制,粘贴方法将其记录在我的比较表中。然后代码返回并执行相反的过程来测试列表1中的列表2;循环遍历列表2并查找列表1中的每个项目。

我的结果意味着匹配结果的数量不一致。列表1中的项目数减去" list1"的结果查找循环不等于列表2中的项目数量减去" list2'中的项目数量。找到循环。其余项目应该只是每个列表中找到的值。

所有项目都是主键,在各自的列表中是唯一的。

curl_exec

请注意:我对VBA很新,并且不是来自开发人员。你可能无法过多地愚弄你的解决方案。

1 个答案:

答案 0 :(得分:0)

我的问题是find函数中的默认参数。我需要设置LookAt:=xlWhole

例如,列表1 =(1,2,32,142)和列表2 =(1,2,3,132)

为了我的目的,32不在列表2中但没有设置该参数,当搜索32时,find函数返回结果,因为它在包含132的单元格中找到它

以下是现在为我工作的代码。谢谢你的帮助

Public Sub compare_list()
Dim wsList2 As Worksheet
Dim wsList1 As Worksheet
Dim wsCompare As Worksheet
Dim found1 As Range
Dim found2 As Range
Dim myCell As Range
Dim countList2 As Integer
Dim countList1 As Integer
Dim listDiff As Integer
Dim commonList2 As Integer
Dim commonList1 As Integer
Dim diffList1 As Integer
Dim diffList2 As Integer


Set wsList2 = Worksheets("List2")
Set wsList1 = Worksheets("List1")
Set wsCompare = Worksheets("Compare")

Application.ScreenUpdating = False
Application.CutCopyMode = False


'Check each value in the client_id list created by List1 to find an equal     value in List2's list

Set myCell = wsList1.Range("A1")

Do Until myCell.Value = ""

Set found1 = wsList2.Range("a1",   wsList2.Range("A1048576").End(xlUp)).Find(what:=myCell.Value, LookAt:=xlWhole)
    If found1 Is Nothing Then
    myCell.Copy
    wsCompare.Range("A1048576").End(xlUp).Offset(1, 0).PasteSpecial
    Else
    myCell.Copy
    wsCompare.Range("G1048576").End(xlUp).Offset(1, 0).PasteSpecial
    End If

Set myCell = myCell.Offset(1, 0)

Loop

'Check each value in the client_id list created by List2 to find an equesl value in List1's list

Set myCell = wsList2.Range("A1")

Do Until myCell.Value = ""

Set found2 = wsList1.Range("a1",  wsList1.Range("A1048576").End(xlUp)).Find(what:=myCell.Value, LookAt:=xlWhole)
    If found2 Is Nothing Then
    myCell.Copy
    wsCompare.Range("B1048576").End(xlUp).Offset(1, 0).PasteSpecial
    Else
    myCell.Copy
    wsCompare.Range("F1048576").End(xlUp).Offset(1, 0).PasteSpecial
    End If

Set myCell = myCell.Offset(1, 0)

 Loop

Application.ScreenUpdating = True

 wsCompare.Activate

'test logic of result
countList1 = wsList1.Range("a2", wsList1.Range("A1048576").End(xlUp)).Rows.count
countList2 = wsList2.Range("a2", wsList2.Range("a1048576").End(xlUp)).Rows.count


diffList1 = (wsCompare.Range("a2",   wsCompare.Range("A1048576").End(xlUp)).Rows.count - 1)
diffList2 = (wsCompare.Range("b2",     wsCompare.Range("b1048576").End(xlUp)).Rows.count - 1)

listDiff = Abs(countList1 - countList2)

commonList2 = (countList2 - diffList2)
commonList1 = (countList1 - diffList1)

MsgBox "List2 has " & commonList2 & " in common with List1" & vbCrLf & "List1     has " & commonList1 & " in common with List2"


End Sub