VBA代码突出显示excel中的重复列

时间:2017-02-24 15:20:53

标签: excel-vba vba excel

我正在使用VBA来验证Excel工作表的内容。我想在第一列中使用唯一值,并且能够使用另一列上的外键确定这些值的有效性。这是我必须验证的唯一条目:

Private Sub Worksheet_Change(ByVal Target As Range)

    If Application.CountIf(Range("A:A"), Target) > 1 Then
        MsgBox "Duplicate Data", vbCritical, "Remove Data"
        Target.Value = ""
    End If
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

End Sub

它可以防止第一行重复输入。但我真正想要的是能够通过在已填充的电子表格上运行宏来检测重复,并突出显示无效字段。

1 个答案:

答案 0 :(得分:0)

这应该可以解决问题:

Sub sbHighlightDuplicatesInColumn()
Dim lastCol As Long
Dim matchFoundIndex As Long
Dim iCntr As Long

lastCol = Sheets("Sheet1").Range("A1").SpecialCells(xlCellTypeLastCell).Column
For iCntr = 1 To lastCol
    If Cells(1, iCntr) <> "" Then
        matchFoundIndex = WorksheetFunction.Match(Cells(1, iCntr), Range(Cells(1, 1), Cells(1, iCntr)), 0)
        If iCntr <> matchFoundIndex Then
            Sheets("Sheet1").Cells(1, iCntr).Interior.Color = vbYellow
        End If
    End If
Next
End Sub
相关问题