Home » excel » excel vba – Lookup Partial String To Return Data From Corresponding Columns and Rows (VBA)

excel vba – Lookup Partial String To Return Data From Corresponding Columns and Rows (VBA)

Posted by: admin April 23, 2020 Leave a comment


I have a client/job database for which I would like to be able to do partial and full searches. This database includes at least 19 different pieces of data, e.g. Company Name, Company Address, Point-Of-Contact, job start and end date, job revenue etc..

I have a single search field, where I can enter different column inputs and search for the relevant client. For example, If I key in Client Name, it will return all jobs with that client. If I search 201X, it will return all jobs done in 201X. This returned data is populated as a list below my search box.

My current problem is I am unable to do partial searches. E.g. I must type in ‘General Electric’, as opposed to just ‘Electric’. The VBA code I’ve used is provided below. Any help will be greatly appreciated!

Option Compare Text 
Sub SearchClientRecord()

Dim Search As String 
Dim Finalrow As Integer 
Dim SearchFinalRow As Integer 
Dim i As Integer 
Dim scs As Worksheet 
Dim scd As Worksheet

Set scs = Sheets("Client Search") 
Set scd = Sheets("Client Database")


Search = scs.Range("C12") 
Finalrow = scd.Range("D100000").End(xlUp).Row 
SearchFinalRow = scs.Range("D100000").End(xlUp).Row

For j = 3 To 19 
For i = 19 To Finalrow

If scd.Cells(i, j) Like Search Then 
scd.Range(scd.Cells(i, 3), scd.Cells(i, 19)).Copy
scs.Range("C100000").End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats 
End If 
Next i 
Next j 
    scs.Range("$C$18:$S$1009").RemoveDuplicates Columns:=Array(1, 2, 3, 4, 5, 6 _ , 7), Header:=xlYes

Call Border Columns("C:S").HorizontalAlignment = xlCenter

End Sub 
Sub AddJobDetail() 
End Sub
How to&Answers:

Use the Instr function to find one string within another – https://msdn.microsoft.com/en-us/library/8460tsh1(v=vs.90).aspx

e.g. replace

If scd.Cells(i, j) Like Search Then 


if Instr(scd.Cells(i,j), Search) > -1 then

But of course be careful typing ‘Electric’ if you have ‘General Electric’ and ‘Electric Motors’ 🙂