VBA循环两个excel列中的值
我试图通过两个excel列循环,并确定第一列中的值是否存在于第二列。 我在VBA编程方面相当新,而且还没有编程。
我的代码,当我通过F8运行它,如果它发现一个值,它会写“匹配”,但它会保持循环,最终重写为“不匹配”。 你能告诉我如何解决这个问题吗?
谢谢
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
试试这个:修改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
匹配后只需添加Exit For
如下所示:
If act2 = act1 Then dbsheet2.Cells(y, 3).Value = "Match" Exit For Else
很好,你想出了一些代码。 这样做有很多简单的方法,如果你喜欢,你可以使用,
方法1:
如果数据在列A and B
,则在Column C
input以下公式,然后向下拖动,
=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