2015-11-03 37 views
1

爲什麼此代碼無法正常工作?任務是僅在首先發生時纔將(str。和strasse)從正確的位置替換。在測試中,它什麼都不做。將字母替換爲其他的錯誤

我想錯誤是在這條線: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 

我已經測試的第二個碼是:

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」在大街而不課。 ...

+0

*僅whenn第一齣現正確的位置* - >你的意思是,如果'.str'或'.strasse'是**正確單元格中的最多**單詞值? –

+0

請顯示您的預期輸出 –

+0

另外,在您的第一個宏中,您正在'x'的** REVERSED **字符串中搜索'strArr(b)'。除非您搜索'strArr(b)'的反向,否則您將永遠無法找到它。 –

回答

0

由於您已將您正在搜索的字符串反轉,因此所查找的字符串也需要反轉。所以"strArr(b)"應該變成StrReverse(strArr(b))。下面的代碼糾正了這種情況,並更改了要顯示的數組文本。

此外,我注意到您的替換文本沒有點。您可能需要使用".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 

結果...

enter image description here

相關問題