2017-02-24 105 views
1

我正在使用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 

它防止在第一行中出現重複條目​​。但我真正想要的是能夠通過在已經填充的電子表格上運行宏來檢測重複,並且突出顯示無效字段。

回答

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 
+0

真棒!有效。感謝@VBA_SQL_Programmer爲您的時間和精力。真的很感謝 –

+0

沒問題。我很高興它爲你解決。 –

+0

你能幫我解決我在這裏發佈的問題嗎?:http://stackoverflow.com/questions/42451868/setting-foreign-keys-constraint-in-excel-using-vba –