简体   繁体   English

突出显示单元格中是否有 2 个不同的值

[英]Highlight if 2 different values in a cell

would anyone be able to help?有人能帮忙吗? I am trying to write VBA to highlight if the cell has 2 different values.我正在尝试编写 VBA 以突出显示单元格是否有 2 个不同的值。 It seems to highlight all including the same name appear twice.它似乎突出显示所有包括同名的出现两次。 Thanks for any help!谢谢你的帮助!

Sub CountTwoOrMoreDifferent()
Dim myRange As Long
myRange = Cells(Rows.Count, "A").End(xlUp).Row
Range("A2:A" & myRange).Select
For Each AnimalName In Selection
    AnimalNameMoreThan2 = AnimalName.Value
    If InStr(AnimalNameMoreThan2, "Cat") + _
    InStr(AnimalNameMoreThan2, "Dog") + _
    InStr(AnimalNameMoreThan2, "Cow") _
    + InStr(AnimalNameMoreThan2, "Chicken") + _
    InStr(AnimalNameMoreThan2, "Snake") + _
    InStr(AnimalNameMoreThan2, "Tums") + _
    InStr(AnimalNameMoreThan2, "Drop") > 1 Then
    AnimalName.Interior.Color = vbRed
    End If
    Next AnimalName
End Sub

Data in column A A列中的数据

Sample Data样本数据

在此处输入图像描述

You can use this code.您可以使用此代码。

It is split into two parts它分为两部分

  • a sub - which does the check per cell.一个 sub - 它对每个单元格进行检查。
  • a function that checks if there is a duplicate within an array.检查数组中是否存在重复项的函数。 It returns true in case there is at least one dup.如果至少有一个重复,则返回 true。
Public Sub highlightDuplicateValues()

'get Range to check
Dim lastRow As Long, rgToCheck As Range
With ActiveSheet
    lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    Set rgToCheck = .Range("A2:A" & lastRow)        'no need to select!
End With

Dim c As Range, arrValuesInCell As Variant
Dim i As Long

For Each c In rgToCheck.Cells
    'get an array of values/animals in cell
    arrValuesInCell = Split(c.Value, ";")
    
    'now check for each value if it has a dup - if yes color red and exit check
    For i = LBound(arrValuesInCell) To UBound(arrValuesInCell)
        If hasDupInArray(arrValuesInCell, i) = True Then
            c.Interior.Color = vbRed
            Exit For
        End If
    Next
Next

End Sub

Private Function hasDupInArray(arrValues As Variant, checkI As Long) As Boolean

'only values after the checkI-value are checked.
'Assumption: previous values have been checked beforehand

Dim varValueToCheck As Variant
varValueToCheck = arrValues(checkI)

Dim i As Long
For i = checkI + 1 To UBound(arrValues)
    If arrValues(i) = varValueToCheck Then
        hasDupInArray = True
        Exit For
    End If
Next
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM