从两张纸中查找重复的值

时间:2018-11-23 05:43:45

标签: excel

我有Excel两张纸 像这样的数据。

sheet1:  2000, 3000, 4500, 300, 2000, 3000      
sheet 2: 300, 2000, 3000, 4550

我运行以下代码以用不同的颜色突出显示两个工作表中的值,其中值符合条件。 但是问题在于,sheet1的所有值2000、3000都用颜色填充,而sheet2的值只有2000、3000一次。 如果与工作表2进行比较,则仅包含一次2000、3000的值 因此,sheet1的第一个值和第二个值都用颜色填充,其余的值(最后两个值)不应为彩色。

非常感谢您的解决方案。

Sub Dupranges()

Dim wr1 As Range, wr2 As Range, Rng1 As Range, Rng2 As Range


Set wr1 = Worksheets("Sheet1").Range("f1:f10")
Set wr2 = Worksheets("Sheet2").Range("g1:g10")


For Each Rng1 In wr1
    Rng1.Value = Rng1.Value
    For Each Rng2 In wr2
        If Rng1.Value = Rng2.Value Then 
            Rng1.Interior.ColorIndex = 43
            Rng2.Interior.ColorIndex = 33
            Exit For
        End If
    Next
Next

MsgBox "Successfully completed"

End Sub

2 个答案:

答案 0 :(得分:0)

我想我得到了您想要的东西,它不漂亮,但是我才刚开始vba。 您必须将范围更改回您的范围

Sub format()

Dim wr1 As Range, wr2 As Range


Set wr1 = Worksheets("Sheet1").Range("a1:a10")
Set wr2 = Worksheets("Sheet2").Range("a1:a10")


For i = 1 To wr1.Count
check_value = wr1.Item(i)
For k = 1 To wr2.Count
    check_value2 = wr2.Item(k)
    If (check_value = check_value2) And (wr2.Item(k).Interior.ColorIndex = 33) And 
(wr1.Item(i).Interior.ColorIndex = 43) Then
    Else
    If (check_value = check_value2) And (wr2.Item(k).Interior.ColorIndex <> 33) And 
(wr1.Item(i).Interior.ColorIndex <> 43) And (wr2.Item(k).Value > "") Then
    wr1.Item(i).Interior.ColorIndex = 43
    wr2.Item(k).Interior.ColorIndex = 33
        Exit For
    End If
   End If
Next
Next


MsgBox "Successfully completed"

End Sub

希望您发现这很有用

答案 1 :(得分:0)

您的代码几乎可以,但是您可以节省将范围移动到数组的时间。

Option Explicit

Sub showDupes(src As Range, tgt As Range)
    Dim c As Range, i As Long, srcVal
    Dim a As Variant, found As Boolean

    a = tgt.Value2   'store tgt into array for speed

    For Each c In src
        srcVal = c.Value2
        found = False
        For i = 1 To UBound(a)
            If a(i, 1) = srcVal Then
                found = True
                Exit For
            End If
        Next i
        If found Then
            'highlight in src
            c.Interior.ColorIndex = 43
            'highlight in tgt
            tgt.Cells(i, 1).Interior.ColorIndex = 43
        End If
    Next c
End Sub

Sub showDupes_test()
    showDupes Sheet1.Range("B4").CurrentRegion, Sheet2.Range("b4").CurrentRegion
End Sub

请注意,在此版本中,如果tgt具有本地重复项,则仅突出显示第一个。