Home » excel » excel – Match whole word/phrase and replace

excel – Match whole word/phrase and replace

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’m trying to replace a string with another but the problem is that the string is matching some other string partially.

I am trying to create a function that searches each line in another spreadsheet and returns that row if my search phrase is found. Script works wonderfully when used with longer words or unique words or I enter code phrases as the search criteria. The problem is that if the string is matching some other string partially it gets copied and I get a lot of wrong results.

I need the function to stop looking within the words for results and instead look at the word or phrase as a whole for a match.

This is my script so far:

Sub Light()
  Dim rng1 As Range
  Dim fnd1 As String
  fnd1 = "Quantity"

  Sheets("TEST").Activate
  Set rng1 = Sheets("TEST").Cells.Find(fnd1)
  If Not rng1 Is Nothing Then
    Range(Cells(rng1.Row, rng1.Column), Cells(Rows.Count, rng1.Column).End(xlUp)).Copy _
      Sheets("TEMPLATE").Range("A5")
    Cells(1, 1).Select
  End If

And here I have my problem because second search criteria is met partially and gets copied.

  Dim rng2 As Range
  Dim fnd2 As String
  fnd2 = "Quantity order min"
  Sheets("TEST").Activate
  Set rng2 = Sheets("TEST").Cells.Find(fnd2)
  If Not rng2 Is Nothing Then
    Range(Cells(rng2.Row, rng2.Column), Cells(Rows.Count, rng2.Column).End(xlUp)).Copy _
      Sheets("TEMPLATE").Range("C5")
    Cells(1, 1).Select
  End If
How to&Answers:

There is bound to be a better answer and this may not even achieve your desired result – but for want of anything else so far!:

Sub Light()
Dim rng1 As Range
Dim fnd1 As String
Dim rng2 As Range
Dim fnd2 As String

fnd1 = "Quantity"
fnd2 = "Quantity order min"

Sheets("TEST").Activate
Set rng1 = Sheets("TEST").Cells.Find(fnd1)
If Not rng1 Is Nothing Then
If Sheets("TEST").Cells.Find(fnd1, LookIn:=xlValues, lookat:=xlWhole) > 1 Then
   Sheets("TEMPLATE").Select
Range("A5").Select
ActiveCell.FormulaR1C1 = fnd1
End If
End If
Sheets("TEST").Activate
Set rng2 = Sheets("TEST").Cells.Find(fnd2)
If Not rng2 Is Nothing Then
If Sheets("TEST").Cells.Find(fnd2, LookIn:=xlValues, lookat:=xlWhole) > 1 Then
   Sheets("TEMPLATE").Select
Range("C5").Select
ActiveCell.FormulaR1C1 = fnd2
End If
End If
End Sub