比较单元格值与列和返回结果

时间:2017-10-10 19:11:30

标签: vba excel-vba excel

我试图将单元格的值与整列进行比较,直到有数据为止,我无法生成正确的结果,因为只有来自循环的最后一个值才会放入单元格中还需要在其他单元格中显示错误匹配结果的计数。

Sub test_blank()
Dim i As Integer, da As Long
da = Range("a2", Range("a15000").End(xlUp)).Count
For i = 1 To da
    If Range("A" & i).Value = Range("b2").Value Then
        Range("b3") = "match"
    Else
        Range("b3") = "does not match"
    End If
Next
End Sub

1 个答案:

答案 0 :(得分:1)

我认为你想要实现的目标可以像这样完成

Sub test_blank()
    Dim count As Integer
    Dim doesntMatch As Boolean

    'Set a counter for the number of times it doesn't match
    count = 0
    'Set a flag if a value doesn't match
    doesntMatch = False

    'Go through each cell in the column (starting from A2)
    For Each cell In Range("A2", "A" & Cells(Rows.count, 1).End(xlUp).Row)
        'If the value is found write match and leave the loop
        If (cell <> Range("B2").Value) Then
            doesntMatch = True
            count = count + 1
        End If
    Next cell

    'If a value didn't match at some point
    If (doesntMatch) Then
        'Display "Doesn't match" and the counter
        Range("B3").Value = "Doesn't match"
        Range("C3").Value = count
    'If always matched
    Else
        'Display "Match"
        Range("B3").Value = "Match"
    End If

End Sub

使用逻辑

Checking every cell
    If the cell doesn't match, increment the counter and activate the flag

If the flag is activated
    Display the message and the counter
If the flag isn't activated
    Display the message
相关问题