Search code examples
excelvbadatabaseduplicatesreal-time

Searching duplicates in real time while user is filling a UserForm, VBA Excel


I'm facing a problem. I'm actually using this to check if a duplicate exists in my table :

If Not IsError(Application.Match(Me.txtCompanyName.Value, ws.ListObjects("Companies").ListColumns("company_name").Range, 0)) Then

   MsgBox "A company is already registered with this name"

This code is executed on a button click.

I'm wondering if there's a way to check in real time if duplicate exists in my table while user is typing better than waiting for him to click the button as we can see on some web forms. I tried to use AfterUpdate on Me.txtCompanyName but it's not really real time.

Thanks for your answers any help would be highly appreciated.

Regards.


Solution

  • As ashleedawg said in the comments I used the KeyUp event to figure out.

    Here is the answer to my question if it can be useful to someone else.

    Private Sub myText_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
        Dim srch As String
        Dim str As String
        Dim ws As Worksheet
        
        Set ws = Worksheets("myWorksheet")
            
        iRow = ws.Range("B1", ws.Range("B1").End(xlDown)).Rows.Count
        
        If Me.txtRaisonSociale.Value <> "" Then
        
            For i = 2 To iRow
            
                srch = ws.Range("B" & i).Value
                
                If InStr(srch, Trim(ModuleFonctions.setRegexRS(Me.myText.Value))) > 0 Then
                    str = str + srch + Chr(13) & Chr(10)
                End If
                
            Next i
            Me.lblInfo.Caption = "Duplicate(s) found :" & Chr(13) & Chr(10) & str
        
        Else
            Me.lblInfo.Caption = ""
        End If
            
    End Sub
    
    

    I build a string in a list with all duplicates found. then I set the string as a label caption.