使用VBA替换多值Excel

时间:2015-02-18 05:46:53

标签: excel vba excel-vba excel-formula excel-2010

我在VBA的帮助下创建了一个工作函数(由其他人编写)来替换多个字符串,我的问题是它替换了第一个实例而不是字符串的完整值,我将用一个例子来解释。

旧价值

  1. 汽车
  2. 汽车轮胎
  3. 新值

    1. 自行车
    2. 总线
    3. 现在这个功能可以取代Car with Bike,但是当涉及到“Car Tire”时它取代了Car with Bike并忽略了“Tire”给我最终输出为“Bike Round Tire”但答案应该是Bus

      Function SubstituteMultiple(text As String, old_text As Range, new_text As Range)
      Dim i As Single
      For i = 1 To old_text.Cells.Count
          Result = Replace(text, old_text.Cells(i), new_text.Cells(i))
          text = Result
      Next i
      SubstituteMultiple = Result
      End Function
      

      这个功能非常有用,但需要完善。

      此致

1 个答案:

答案 0 :(得分:0)

如果考虑完整的单元格值,那么:

Function SubstituteMultiple(text As String, old_text As Range, new_text As Range)

    Dim i As Single, Result as String
    Result = text
    For i = 1 To old_text.Cells.Count
        If text = old_text.Cells(i).Value Then
            Result = new_text.Cells(i).Value
            Exit For
        End If
    Next i
    SubstituteMultiple = Result

End Function