如果单元格中的值在下一列中查找并将其替换为VBA

时间:2016-04-26 13:19:07

标签: excel vba excel-vba if-statement

我正在使用此函数替换值:

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

像这样:

enter image description here

因此函数的工作方式如此,它会检查列C中的值是否也在列A中。如果找到它,将使用列B中的值替换它。

我想调整此功能,以便只有找到A列中的确切值才能进行替换。与图片中一样,C列中的文字成为E列中的文字,a b abaaaabaaa列中的值A不存在。

目前函数执行此操作,这是错误的,因为值abaaa不应该替换它:

enter image description here

1 个答案:

答案 0 :(得分:1)

试试这个

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

被称为

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