简体   繁体   中英

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:

在此处输入图片说明

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 ab 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:

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM