+ Reply to Thread
Results 1 to 2 of 2

Check cell range for closest match of cell value (multiple words)

Hybrid View

  1. #1
    Registered User
    Join Date
    10-11-2004
    Posts
    8

    Red face Check cell range for closest match of cell value (multiple words)

    Hi,

    I have a collection of words that I'd like to search for against a single column of phrases, when the closest possible match is found, it should return an adjacent value from the column of phrases searched. The complexity I have, is for each collection of words, i need to try all possible combinations of match.

    Example. I have the following collection of words in A1

    Collection of words
    A1: word1 word2 word3

    I need to search the entire column of B to find the best match.

    A Best match would contain all words & in the order of the collection of words.

    In the example below: B5 wins.

    B5 word1 word2 word3 word4

    If B5 didn't exist, a subsequent best match would be greatest number of words in any order.

    In this example, B3 word3 word2 word1 would win, (pretending B5 doesn't exist) since there's no exact match, the adjacent value in C3, is 3. This is then populated to D1.

    Single column of phrases
    B1 word1 word3
    B2 word1
    B3 word3 word2 word1
    B4 word1 word2
    B5 word1 word2 word3 word4

    Adjacent value to return
    C1 1
    C2 2
    C3 3
    C4 4
    C5 5

    Results
    D1 3
    D2
    D3
    D4
    D5 5

    Hopefully explained myself well enough for others to follow, am hugely appreciative to anyone who can help me with this.

    Best Rgds

    Marcus

  2. #2
    Forum Expert
    Join Date
    01-23-2013
    Location
    USA
    MS-Off Ver
    Microsoft 365 aka Office 365
    Posts
    3,863

    Re: Check cell range for closest match of cell value (multiple words)

    Hi Marcus,

    Try the following Macro which is included in the attached file. This should get us started. I have no idea what you want in Columns 'C' and Column 'D' and I don't know how to get (and/or calculate) those values:
    Option Explicit
    Option Compare Text   'Instr Case Insensitive Compare
    
    Sub ClearColumnE()
      Range("E:E").ClearContents
    End Sub
    
    Sub CreateListsOfMatches()
    
      Dim myDictionary As Object
    
      Dim myRange As Range
      Dim r As Range
        
      Dim i As Long
      Dim iLastIndex As Long
      Dim iLastRowUsedInColumnB As Long
      Dim iMatchCount As Long
      Dim iPos As Long
      Dim iRow As Long
      
      Dim a() As String
      Dim sRange As String
      Dim sSourcePhrase As String
      Dim sToken As String
      Dim sValueColumnB As String
      
      '''''''''''''''''''''''''''''''''''''''''''''''''''
      'Initialization
      '''''''''''''''''''''''''''''''''''''''''''''''''''
      
      'Create the Source dictionary object
      'KEY:   Data Word
      'ITEM:  Count of Data word in Source Phrase (Usually 1)
      Set myDictionary = CreateObject("scripting.dictionary")
      myDictionary.CompareMode = vbTextCompare 'case insensitive
      
      'Clear the Destination Area
      Call ClearColumnE
      
      '''''''''''''''''''''''''''''''''''''''''''''''''''
      'Create the Source Phrase and the List of Source Words
      '''''''''''''''''''''''''''''''''''''''''''''''''''
      
      'Get the Source Phrase (remove leading and trailing spaces)
      sSourcePhrase = Trim(Range("A1").Value)
        
      'Parse the Source Phrase Into Words
      iLastIndex = LjmParseString(sSourcePhrase, a)
      
      'Put the Words in the Source Dictionary
      For i = 0 To iLastIndex
     
        'Process each string and put it into the dictionary and/or increment the count for that item
        sToken = a(i)
        If myDictionary.exists(sToken) Then
          myDictionary.Item(sToken) = myDictionary.Item(sToken) + 1
        Else
          myDictionary.Add sToken, 1
        End If
      Next i
      
      
      '''''''''''''''''''''''''''''''''''''''''''''''''''
      'Process One Data Row at a time
      '''''''''''''''''''''''''''''''''''''''''''''''''''
      
      'Find the Last Row Used In Column 'B'
      iLastRowUsedInColumnB = Cells.Find(What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    
      'Create the Range that is used in Column 'B'
      sRange = "B1:B" & iLastRowUsedInColumnB
      Set myRange = Range(sRange)
      
      For Each r In myRange
      
        'Get the Row Number
        iRow = r.Row
      
        'Get the Phrase to be tested (remove leading and trailing spaces)
        sValueColumnB = Trim(r.Value)
        
        'Parse the Target Phrase Into Words
        iLastIndex = LjmParseString(sValueColumnB, a)
        
        'Try to match the entire phrase (case Insensitive)
        'Put the results in Column 'E' if a match
        iPos = InStr(sValueColumnB, sSourcePhrase)
        If iPos > 0 Then
          Cells(iRow, "E").Value = "Entire Phrase Match"
        Else
        
          'Initialize the Match Count
          iMatchCount = 0
        
          'Find the Number of Matches in the Phrase to be tested
          For i = 0 To iLastIndex
            sToken = a(i)
            If myDictionary.exists(sToken) Then
              iMatchCount = iMatchCount + 1
            End If
          Next i
          
          'Output the Results
          If iMatchCount = 1 Then
            Cells(iRow, "E").Value = "1 Match"
          Else
            Cells(iRow, "E").Value = iMatchCount & " Matches"
          End If
        End If
      
      
      Next r
      
      
      'Clear the object pointers
      Set myDictionary = Nothing
      Set myRange = Nothing
    
    End Sub
    
    Function LjmParseString(InputString As String, ByRef sArray() As String) As Integer
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    '
    ' This parses a space delimited string into an array of tokens.
    ' Leading and trailing spaces are stripped from the string in the process.
    '
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    
      Dim i As Integer
      Dim LastNonEmpty As Integer
      Dim iSplitIndex As Integer
    
     'Initialization
      LastNonEmpty = -1
      
      'Split the string into tokens (space delimited)
      sArray = Split(InputString, " ")
      iSplitIndex = UBound(sArray)
    
     'Remove the null tokens
      For i = 0 To iSplitIndex
      
        'Remove leading and trailing spaces
        sArray(i) = Trim(sArray(i))
        
        If sArray(i) <> "" Then
           'Get rid of all the whitespace
            LastNonEmpty = LastNonEmpty + 1
            sArray(LastNonEmpty) = sArray(i)
        End If
      Next i
    
    
     'Return the number of indices
      LjmParseString = LastNonEmpty
      
    End Function
    The solution uses a 'Scripting Dictionary' which is useful when you have a list of items that must be compared in no special order. For additional information see: http://www.snb-vba.eu/VBA_Dictionary_en.html

    Lewis
    Last edited by LJMetzger; 11-22-2015 at 11:27 AM. Reason: Adding Scripting Dictionary note

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. check for match of cell to range of cells only if another cell is equal to X
    By rfigueroa1976 in forum Excel Formulas & Functions
    Replies: 6
    Last Post: 02-25-2015, 07:51 PM
  2. Search for multiple words in range of cells...answer in adjacent cell
    By TheDudestMonk in forum Excel Formulas & Functions
    Replies: 6
    Last Post: 08-13-2013, 07:49 AM
  3. [SOLVED] Looking up value by closest match & determining cell address.
    By clique in forum Excel Formulas & Functions
    Replies: 7
    Last Post: 03-01-2013, 11:40 AM
  4. [SOLVED] Match Formula to Check if Cell Value is Within a Numeric Range Table
    By dieseldogpi in forum Excel Formulas & Functions
    Replies: 3
    Last Post: 08-16-2012, 12:04 PM
  5. [SOLVED] Find the closest match to a cell , but with a condition.
    By Sarangsood in forum Excel General
    Replies: 8
    Last Post: 12-31-2011, 05:00 AM
  6. find the closest match of a cell from a column when another cell reaches a value
    By Sarangsood in forum Excel Programming / VBA / Macros
    Replies: 2
    Last Post: 08-11-2011, 12:58 AM
  7. Check one Cell for multiple words in one macro line?
    By Hutas in forum Excel Programming / VBA / Macros
    Replies: 1
    Last Post: 01-08-2005, 10:34 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1