Running proximity searches in Excel
top of page

Running proximity searches in Excel

It's possible to run proximity searches in Excel using the below Visual Basic code. It will highlight any cells in which two given terms appear within a number of words that you set. Simply copy the vba code into a new module in the project list:



. . . the macro will run and prompt you to enter the cell in which the search should begin, and then prompt you to enter the first term, the second term, and the highest number of words which should appear between these terms.



This macro will only search for the terms in the order in which you enter them. It will find when the second term is within X number of words after the first term, but not vice versa.



Thanks to will266 for posting this code here.


Sub proximitySearch()

Dim startCell: startCell = InputBox("Enter Starting cell for search; i.e. B2", "Starting Cell")

Dim termOne: termOne = InputBox("Enter first search term", "Search Term 1")

Dim termTwo: termTwo = InputBox("Enter second search term", "Search Term 2")

Dim proximity: proximity = InputBox("Enter maximum distance between terms", "Proximity Value")


Dim rng As Range, r As Range

Set rng = Range(startCell, Range("a" & Rows.Count).End(xlUp))

rng.Interior.ColorIndex = xlNone

With CreateObject("VBScript.RegExp")

.IgnoreCase = True

.Pattern = termOne + "\S*(\s\S+){0," + proximity + "} " + termTwo

For Each r In rng

If .test(r.Value) Then r.Interior.Color = vbRed

Next

End With

End Sub

Sean O'Shea has more than 20 years of experience in the litigation support field with major law firms in New York and San Francisco.   He is an ACEDS Certified eDiscovery Specialist and a Relativity Certified Administrator.

The views expressed in this blog are those of the owner and do not reflect the views or opinions of the owner’s employer.

If you have a question or comment about this blog, please make a submission using the form to the right. 

Your details were sent successfully!

© 2015 by Sean O'Shea . Proudly created with Wix.com

bottom of page