VBA循环遍历两个excel列中的值

标签 vba excel

我正在尝试遍历两个 excel 列并确定第一列中的值是否存在于第二列中。我对 VBA 编程相当陌生,并且有一段时间没有编程了。

我的代码,当我通过 F8 运行它时,如果它找到一个值,它将写入“匹配”,但它会继续循环并最终将其重写为“不匹配”。你能告诉我如何解决这个问题。

谢谢

enter image description here

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/

相关文章:

vba - 需要帮助了解不合格的范围

sql - 在 mySQL 中将字符串格式化为日期

mysql - 刷新数据时保留公式

vba - 选择不并集的多个动态范围

excel - 如果#REF!然后隐藏某些行

vba - Sheet.Activate 更改工作表,但继续编辑上一张工作表上的数据

mysql - 时间戳格式 dd/mm/yyyy hh :mm:ss to yyyy-mm-dd hh:mm:ss - MySQL

excel - 带输入框的 If 语句 - 不起作用

wcf - 如何将大文件从 MS Word 插件 (VBA) 传输到 Web 服务器?

python - 读取/写入 Excel 文件中的特定位置