将字母replace为其他字符时出错

为什么这个代码不能正常工作? 任务是只有在第一个出现的时候才从正确的位置replace(str。和strasse)。 在testing中,它什么都不做。

我猜这个错误是在这一行: x.Value = StrReverse(Replace(StrReverse(x.Value), strArr(b), "straße", 1, 1))这里是错误。

 Sub strreplace() Dim strArr As Variant Dim b As Byte Dim x As Range strArr = Array("str.", "strasse", """") For Each x In Selection.Cells For b = 0 To UBound(strArr) x.Value = StrReverse(Replace(StrReverse(x.Value), strArr(b), "straße", 1, 1)) Next b Next x End Sub 

我testing的第二个代码是:

 Sub strReplace() Dim strArr As Variant Dim b As Byte strArr = Array("str.", "strasse", """") For Each x In Selection For b = 0 To UBound(strArr) If InStrRev(x, strArr(b)) > 0 Then Selection.Replace x, Replace(x, strArr(b), "straße", InStrRev(x, strArr(b))) End If Next b Next End Sub This code transform example: 

“Lessonstrasse”instraßewithout Lesson …

既然你已经扭转了你search的string,那么被寻找的string也需要颠倒过来。 所以"strArr(b)"应该成为StrReverse(strArr(b)) 。 下面的代码纠正了这个问题,用数组文本来改变。

另外,我注意到你的replace文本没有点。 您可能要使用".straße"而不是"straße" 。 另外,你可能会发现一个用户定义的函数更方便,但是当然,我不知道你是用法上下文。

 Sub strreplace() Application.ScreenUpdating = False Dim strArr As Variant Dim b As Byte Dim x As Range strArr = Array(".Ext1", ".Ext2") For Each x In Selection.Cells For b = 0 To UBound(strArr) x.Value2 = StrReverse(Replace(StrReverse(x.Value2), StrReverse(strArr(b)), "straße", 1, 1)) Next b Next x End Sub 

结果…

在这里输入图像说明