I have a table with address data. I enter these via a user form. AddressID, LastName, FirstName, ZipCode,City
When I click on the SaveButton, I want to check whether the address entered (without AddressID ) is already in the shAdress table.
For example
AddressID, LastName, FirstName, ZipCode,City
1 May Paul 67105 Berlin
2 May Paul 67106 Berlin that’s ok
3 May Paul 67105 Berlin this is wrong!
Up to now, I have been writing the data to the table and then checking for duplicates. However, it would make more sense to check the data before slicing. Can anyone help me with how to do this?
My function to check after insert in the sheet
Function CheckforDuplicateListObject(wksTab As Worksheet, TableName As String) As Boolean
Dim LastRow As Long, LastRowNew As Long
Dim LastCol As Long
Dim i As Long
Dim vardat() As Variant
'Switch off calculations
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.EnableEvents = False
With wksTab
.Activate
'Number of rows and columns to be checked
LastRow = .Range(TableName).Rows.Count
LastCol = Range(TableName).Columns.Count
'Form data field without ID column
'Number of columns varies depending on the table!!!
ReDim vardat(0 To LastCol - 2) As Variant
For i = 2 To LastCol
vardat(i - 2) = i
Next i
'Delete duplicate data records with comparison of the data field
ActiveSheet.ListObjects(TableName).DataBodyRange.RemoveDuplicates Columns:=(vardat), Header:=xlYes
'Number of remaining lines
LastRowNew = .Range(TableName).Rows.Count
End With
''Berechnungen wieder einschalten
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.EnableEvents = True
If LastRowNew < LastRow Then
CheckforDuplicateListObject = True
Else
CheckforDuplicateListObject = False
End If
End Function
Sub testDuplikateListIbjectRows()
If CheckforDuplicateListObject(shListobj, "tbAdressen") = False Then
MsgBox "Die Daten wurden in die Tabelle eingetragen"
Else
MsgBox "Die Daten sind bereits vorhanden"
End If
End Sub