user3536226
user3536226

Reputation: 41

If value in cell look in next column and replace it VBA

I am using this function to replace values :

Public Function replaceWord(t As String)
   For Each c In Columns(1).SpecialCells(2)
   t = Replace(t, c.Value, c.Offset(0, 1).Value)
   Next
   replaceWord = t
End Function

Like this:

enter image description here

So the function work like this, it checks if values in column C are also in column A. If found it, is going to replace it with values in column B.

I would like to adjust this function so only if exact values in column A are found then do the replacement. Like in the picture, where text in column C becomes text in column E, so a b abaaa, as the value abaaa is not present in column A.

At the present the function does this, which is wrong, as value abaaa should not be replaced it:

enter image description here

Upvotes: 0

Views: 1001

Answers (1)

user3598756
user3598756

Reputation: 29421

try this

Option Explicit
Public Function replaceWord(t As String, referenceRng As Range, colOffset as long)
    Dim found As Range
    Dim strng As Variant

    replaceWord = ""
    For Each strng In Split(t, " ")
        Set found = referenceRng.Find(what:=strng, lookAt:=xlWhole, LookIn:=xlValues, MatchCase:=False)
        If found Is Nothing Then
            replaceWord = replaceWord & strng & " "
        Else
            replaceWord = replaceWord & found.Offset(, colOffset ).Value & " "
        End If
    Next strng
    replaceWord = Trim(replaceWord)
End Function

to be called like

Sub test()
    With ThisWorkbook.Worksheets("SheetTest") '<== change it as per your needs
        .Range("E1") = replaceWord(.Range("C1").Value, .Columns(1).SpecialCells(xlCellTypeConstants, xlTextValues), 1)
    End With
End Sub

Upvotes: 1

Related Questions