我正在使用此函数替换值:
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
像这样:
因此函数的工作方式如此,它会检查列C
中的值是否也在列A
中。如果找到它,将使用列B
中的值替换它。
我想调整此功能,以便只有找到A
列中的确切值才能进行替换。与图片中一样,C
列中的文字成为E
列中的文字,a b abaaa
,abaaa
列中的值A
不存在。
目前函数执行此操作,这是错误的,因为值abaaa
不应该替换它:
答案 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