我正在尝试创建一个宏,该宏将在输入文本的列中突出显示重复项。
我有54列,并希望在输入文本时突出显示每列中的重复项。方案是:如果在B列中两次输入“ STAPLES”,则单元格(B3,B22)将突出显示。我想要一个可以对每一列执行此操作的宏,因此,如果在列E中仅输入“ STAPLES”,则什么也不会发生。
使用条件格式= COUNTIF不一定有帮助(由于将列复制到新工作表的工作流程)。
我已经有了这个宏:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim Rng As Range
Dim cel As Range
'Test for duplicates in a single column
'Duplicates will be highlighted in red
Set Rng = Range(Range("C1"), Range("C" & Rows.Count).End(xlUp))
For Each cel In Rng
If WorksheetFunction.CountIf(Rng, cel.Value) > 1 Then
cel.Interior.ColorIndex = 3
End If
Next cel
End Sub
它可以正常运行,但仅适用于一列(“ C”)。
如何将范围设置为活动列?
我试图将Rng更改为
'Set Rng = Range(ActiveCell,ActiveCell.Column.End(xlUp))
但这显然是错误的。
有任何想法吗?
试试这个:
Set Rng = Range(Cells(1, Target.Column), Cells(Rows.Count, Target.Column).End(xlUp))
最好使用Worksheet_Change
event代替Worksheet_SelectionChange
。
顺便说一句,复制品有特殊的CF:
UPD:如果您想使用VBA,请尝试以下代码:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Rng As Range
Dim cel As Range
Dim col As Range
Dim c As Range
Dim firstAddress As String
'Duplicates will be highlighted in red
Target.Interior.ColorIndex = xlNone
For Each col In Target.Columns
Set Rng = Range(Cells(1, col.Column), Cells(Rows.Count, col.Column).End(xlUp))
Debug.Print Rng.Address
For Each cel In col
If WorksheetFunction.CountIf(Rng, cel.Value) > 1 Then
Set c = Rng.Find(What:=cel.Value, LookIn:=xlValues)
If Not c Is Nothing Then
firstAddress = c.Address
Do
c.Interior.ColorIndex = 3
Set c = Rng.FindNext(c)
Loop While Not c Is Nothing And c.Address <> firstAddress
End If
End If
Next
Next col
End Sub
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句