检查同一行中单元格中的匹配数据?

时间:2013-12-13 01:01:11

标签: excel-vba match vba excel

VBA新手在这里。为了对信息上传执行质量检查,我需要检查某些信息行,以查看在列D和D中输入的字符串是否输入。 F是相同的 - 如果没有,我想突出显示该行并弹出一个消息框。

我需要检查的这些特定信息行由H列中的字符串表示。

欢迎使用公式答案,但我更喜欢将其放在VBA中,因为信息总是在变化,我需要查看的行总是在变化。

到目前为止,这是我正在使用的内容:

Dim ws As Worksheet
Dim sEmail As String
Dim sName As String
Dim rStr As String
Dim bAllClear As Boolean

bAllClear = True
Set ws = ThisWorkbook.Sheets("Upload")

With ws
For i = 1 To 20 'For testing - this needs to be a dynamic range from _
                '1 to end of content
    If .Cells(i, 8).Value = "Completed" Then
        sEmail = .Cells(i, 7).Value
        sName = .Cells(i, 5).Value & " " & .Cells(lRow, 6).Value
        If .Cells(i, 4).Value = sEmail Then
        Else
            .Range(Cells(i, 1), Cells(i, 8)).Interior.ColorIndex = RGB(255, 0, 0)
            bAllClear = False
            rStr = rStr & sName & vbNewLine
    End If
    End If
Next i

If bAllClear = True Then
MsgBox ("All clear!")
Else
MsgBox ("The following learners have mismatched emails between the learner and rater columns." _
        & vbNewLine & vbNewLine & sName & vbNewLine & vbNewLine & _
        "Please double check to make sure each name is listed correctly before continuing.")
End If
End With
End Sub

Data sample

我上面的代码并没有发现列G中的Robert Baratheon被列在D列的Aerys Targaryen旁边。不幸的是,我有一个非常简单的任务的可怕历史,我可能在这里这样做。然后是两个Q:1)如何让我的范围动态?2)我的代码中我做错了什么?

1 个答案:

答案 0 :(得分:2)

我删除了不必要的变量。另外,我注意到您在最后的消息框中显示sName。我想你想展示rStr

这是你在尝试的吗?

Const sMsg1 As String = "The following learners have mismatched " & _
                        "emails between the learner and rater columns."

Const sMsg2 As String = "Please double check to make sure each " & _
                        "name is listed correctly before continuing."

Sub Sample()
    Dim ws As Worksheet
    Dim sName As String, rStr As String
    Dim lRow As Long, i As Long

    Set ws = ThisWorkbook.Sheets("Upload")

    rStr = ""

    With ws
        '~~> Find last row in Col H
        lRow = .Range("H" & .Rows.Count).End(xlUp).Row

        For i = 2 To lRow
            If .Cells(i, 8).Value = "Completed" Then
                If .Cells(i, 4).Value <> .Cells(i, 7).Value Then
                    sName = .Cells(i, 5).Value & " " & .Cells(i, 6).Value
                    '~~> Coloring Red
                    .Range(.Cells(i, 1), .Cells(i, 8)).Interior.ColorIndex = 3
                    rStr = rStr & vbNewLine & sName
                End If
            End If
        Next i

        If rStr = "" Then
            MsgBox ("All clear!")
        Else
            MsgBox (sMsg1 & _
                    vbNewLine & vbNewLine & _
                    rStr & _
                    vbNewLine & vbNewLine & _
                    sMsg2)
        End If
    End With
End Sub

输出样本

enter image description here