我想突出显示列I中所有串联字符串的重复项,如果有突出显示的重复项,则提供一条错误消息。但是,该列中有几个空白单元格,我不希望它们在运行宏时显示为重复项。
我从这里获得了这段代码:
Sub HighlightDuplicateValues()
Dim myRange As Range
Range("I1", Range("I1").End(xlDown)).Select
Set myRange = Selection
For Each myCell In myRange
If Not IsEmpty(ActiveCell.Value) = True Then
If WorksheetFunction.CountIf(myRange, myCell.Value) > 1 Then
myCell.Interior.ColorIndex = 36
End If
End If
Next myCell
End Sub
我绝对没有VBA的经验,但据我所知,这似乎应该可行。但是,最终发生的事情是几乎所有我的数据都被删除了。真不幸。
同样,我想突出显示连接的列I中的所有重复项,但是我不希望这些空白单元格被视为重复项。弹出错误消息的代码将是一个很好的附加好处,但目前并不是我的主要重点。
答案 0 :(得分:4)
如果您想使用VBA,这应该适合您。
Dim mydict As Object
Dim iter As Long
Dim lastrow As Long
Dim errmsg As String
Dim key As Variant
Set mydict = CreateObject("Scripting.Dictionary")
' If you want to use early binding add in the Microsoft Scripting Runtime reference then: Set mydict = new dictionary
With ActiveSheet
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
For iter = 2 To lastrow
If Not mydict.exists(.Cells(iter, "A").Value) Then
mydict.Add .Cells(iter, "A").Value, False
Else
.Cells(iter, "A").Interior.ColorIndex = 36
mydict(.Cells(iter, "A").Value) = True 'Keep track of which values are repeated
End If
Next
End With
errmsg = "Duplicate Values: "
For Each key In mydict
If mydict(key) = True Then 'Dupes
If Not errmsg = "Duplicate Values: " Then 'No extra comma
errmsg = errmsg & ", " & key
Else
errmsg = errmsg & " " & key
End If
End If
Next
MsgBox errmsg