我正在尝试遍历两个 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
关于VBA循环遍历两个excel列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44495418/