查找重复项,如果在单元格旁边是这个,则此值执行此操作

时间:2015-07-09 19:41:17

标签: excel vba duplicates

ColumnA ------------- ColumnB

重复号码---- M-946

重复号码---- M-954

或反之亦然

重复号码---- M-954

重复号码---- M-946

如果在每组2个副本中,作为ColumnB中的值,如上例所述,则为真。然后为A列和B列着色不同的颜色。

为只有2次重复的行着色的代码。 见:

Sub find2duplicatesonly()
      Dim cel As Variant
      Dim myrng As Range

      Set myrng = Range(Range("A2"), Range("A2").End(xlDown))
      myrng.Interior.ColorIndex = xlNone

      For Each cel In myrng
      clr = 10
        If Application.WorksheetFunction.CountIf(myrng, cel) = 2 Then
          cel.Interior.ColorIndex = 26
      clr = clr + 10

      End If
      Next

      MsgBox ("All duplicates found and coloured")

End Sub

这是我在尝试:

我哪里错了?

Public Sub testcode1()
    Dim rngFound As Range
    Dim strFirst As String
    Dim varFind As Variant

    For Each varFind In Array("M-954", "M-946")

        Set rngFound = Columns("B").Find(varFind, Cells(Rows.Count, "B"), xlValues, xlPart)
        If Not rngFound Is Nothing Then

            strFirst = rngFound.Address

            Do
                Set rngFound = Columns("B").Find(varFind, rngFound, xlValues, xlPart)

            Loop While rngFound.Address <> strFirst
            Select Case varFind

                Case "M-954" & "M-946": Call find2duplicatesonly

            End Select

        End If
    Next varFind

End Sub

1 个答案:

答案 0 :(得分:1)

您可以使用Conditional Formatting执行此操作。该页面提到了如何进行特定重复,但如果您的“重复搜索”稍微复杂一些,您可以考虑为条件格式here

制作自己的公式

编辑:经过讨论(见下面的评论),条件格式化可能会起作用,但我不能让它突出显示BOTH单元格,一次只能有一个。因此我写了这个VB代码:

Sub Macro1()
Dim lastRow As Double, matchString1 As String, matchString2 As String
Dim ws As Worksheet
Dim rng As Range, cel As Range

Set ws = ActiveSheet

matchString1 = "Superman"
matchString2 = "Batman"

With ws
    lastRow = .Cells(1, 1).End(xlDown).Row
    Set rng = .Range(.Cells(1, 1), .Cells(lastRow, 1))

    For Each cel In rng
        If (cel.Value = matchString1 And cel.Offset(1, 0).Value = matchString2) Or _
            (cel.Value = matchString2 And cel.Offset(1, 0).Value = matchString1) Then
            With .Range(.Cells(cel.Row, cel.Column), .Cells(cel.Row + 1, cel.Column)).Interior
                .Pattern = xlSolid
                .PatternColorIndex = xlAutomatic
                .Color = 65535
            End With
        End If
    Next cel
End With
End Sub

注意,你可以将“超人”和“蝙蝠侠”改为你需要的任何东西。此外,如果每次都更改,您可以将其设置为引用单元格的值(即matchString1 = Cells(1,2).Value)。这导致了这种着色:Screenshot

另外,你是否需要对前三个“蝙蝠侠”做任何事情?