Query matching 3 sequential numbers

JAYLO

Board Regular
Joined
Apr 3, 2002
Messages
238
I have 2 tables of invoice information where the invoice number is anywhere from 5 to 11 numbers. I am trying to match invoices where any 3 consecutive numbers are the same.
Ex: Invoice # 41598 and Invoice # 98915979 would match since 159 is consecutive in both.
The position of the match within the number doesn't matter.
Thanks!
 

Excel Facts

Last used cell?
Press Ctrl+End to move to what Excel thinks is the last used cell.
Using VBA code this should work

Code:
Option Compare Database
Option Explicit

Private Sub cmdSearch_Click()
    Dim strReturn As String
    
    strReturn = fnSearchInvoices("41598")
    strReturn = fnSearchInvoices("8888888")
End Sub

Private Function fnSearchInvoices(strInvoiceNumber As String) As String
    Dim iIndex As Integer
    Dim invRecSet As DAO.Recordset
    Dim strQuery As String
        
    ' default return
    fnSearchInvoices = ""
    If Len(strInvoiceNumber) < 3 Then
        Exit Function
    End If
    
    For iIndex = 1 To Len(strInvoiceNumber) - 2
        strQuery = "SELECT * FROM tblYourTableName "
        strQuery = strQuery & "WHERE invoiceNumber LIKE '*"
        strQuery = strQuery & Mid(strInvoiceNumber, iIndex, 3) & "*'"
        Set invRecSet = DBEngine(0)(0).OpenRecordset(strQuery)
        If invRecSet.RecordCount <> 0 Then
            fnSearchInvoices = invRecSet.Fields("invoiceNumber")
            Exit Function
        End If
    Next iIndex
End Function

you would want to add code to exclude selecting the row that your strInvoiceNumber came from.
Am empty return string indicates no match.

Jack
 
Upvote 0

Forum statistics

Threads
1,224,594
Messages
6,179,794
Members
452,943
Latest member
Newbie4296

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top