在列中突出显示与主列表不匹配的单元格

时间:2018-12-16 02:16:48

标签: excel vba

我找到了此代码。我想对一组单元格进行错误检查,并希望突出显示与主列表不匹配的单元格。

Dim myRange, v, f, a
Set myRange = Range("P12:P200")
For Each v In Workbooks("Formula_Weighup Audit Auto-Fill Final").Worksheets("Active Master List").Range("J2:J1054")
    Set f = myRange.Find(what:=v, lookat:=xlPart)
    If f Is Nothing Then
        a = f.Address
        Do
            f.Interior.ColorIndex = 5
            Set f = myRange.FindNext
        Loop While f.Address <> a
    End If
Next

MsgBox "Error: R&D #(s) do not exist" & vbNewLine & "(see highlighted items)"
Exit Sub

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找类似的东西。请注意,原始代码中的rangeToCheckmyRange隐式位于ActiveSheet上。

Sub Test()
    Dim masterWb As Workbook
    Set masterWb = Workbooks("Formula_Weighup Audit Auto-Fill Final.xlsm")
    Dim masterList As Range
    Set masterList = masterWb.Sheets("Active Master List").Range("J2:J1054")

    Dim rangeToCheck As Range
    Set rangeToCheck = Range("P12:P200")

    Dim rng As Range, found As Range

    For Each rng In rangeToCheck
        Set found = masterList.Find(what:=rng.Value, Lookat:=xlPart)
        If found Is Nothing Then rng.Interior.ColorIndex = 5
    Next rng

    MsgBox "Error: R&D #(s) do not exist" & vbNewLine & "(see highlighted items)"

End Sub

编辑:基于注释,如果您想在没有找到匹配项的情况下Exit Sub,则可能会更改

If found is Nothing Then rng.Interior.ColorIndex = 5

If found is Nothing Then
    rng.Interior.ColorIndex = 5
    MsgBox "Error: R&D #(s) do not exist" & vbNewLine & "(see highlighted items)"
    Exit Sub
End If

关于您的评论,请注意IF...Then...Else同时具有单行和多行语法。