我正在尝试遍历两个excel列,并确定第一列中的值是否存在于第二列中。我对VBA编程很新,而且还有一段时间没有编程。
我的代码,当我通过F8运行时,如果找到一个值,它将写入"匹配"但它将继续循环并最终将其重写为“#No; No Match"”。你能告诉我如何解决这个问题。
谢谢
Sub loopDb()
Set dbsheet1 = ThisWorkbook.Sheets("Sheet1")
Set dbsheet2 = ThisWorkbook.Sheets("Sheet2")
lr1 = dbsheet1.Cells(Rows.Count, 1).End(xlUp).Row
lr2 = dbsheet2.Cells(Rows.Count, 1).End(xlUp).Row
For x = 2 To lr1
act1 = dbsheet1.Cells(x, 1)
For y = 2 To lr2
act2 = dbsheet2.Cells(y, 1)
If act2 = act1 Then
dbsheet2.Cells(y, 3).Value = "Match"
Else
dbsheet2.Cells(y, 3).Value = "No match"
End If
Next y
Next x
End Sub
答案 0 :(得分:1)
只需在匹配后添加Exit For
如下所示:
If act2 = act1 Then
dbsheet2.Cells(y, 3).Value = "Match"
Exit For
Else
答案 1 :(得分:1)
试试这个: 修改If-Else,如下所示
If Not dbsheet2.Cells(y, 3).Value = "Match" Then
'Only compare if previoulsy not done or resulted in "No match"
If act2 = act1 Then
dbsheet2.Cells(y, 3).Value = "Match"
Else
dbsheet2.Cells(y, 3).Value = "No match"
End If
End If
答案 2 :(得分:1)
很好,你想出了一些代码。有更简单的方法,你可以随意使用,
方法1:
如果数据位于列A and B
中,请在Column C
中输入以下公式并向下拖动,
=IF(IFERROR(MATCH(A1,B:B,0),FALSE),"Match","No Match")
此公式将A列中的值与B列匹配,并根据true / false打印。
方法2:
在VBA中使用Match
公式而不是运行2个不同的循环,如果行数更多,可能会占用更多时间。
下面的代码也为您提供了类似的输出。
Sub match()
Dim i As Long
For i = 1 To Cells(Rows.Count, 1).End(xlUp).Row
If IsError(Application.match(Cells(i, 1), Range("B:B"), 0)) Then
Cells(i, 3) = "No Match"
Else
Cells(i, 3) = "Match"
End If
Next i
End Sub