2016-02-24 34 views
2

我正在反覆使用以下代碼。有沒有更好的選擇。如何一次替換多個字符串

Dim strtxt as string 
strtxt = Replace(strtxt, "String1", "") 
strtxt = Replace(strtxt, "String2", "") 
strtxt = Replace(strtxt, "String3", "") 
strtxt = Replace(strtxt, "String4", "") 
strtxt = Replace(strtxt, "String5", "") 
strtxt = Replace(strtxt, "String6", "") 
strtxt = Replace(strtxt, "String7", "") 
+0

那麼你是不是該代碼是不合法的,因爲沒有')'。你的方式很清楚,並且和其他方式一樣好。 –

+0

只是忘了。添加。你可以補充說。 – Rahul

+1

目標是明確的代碼,明確它在做什麼。你的方式很棒。 –

回答

1

試試這個

Dim mLBound As Long 
Dim mUBound As Long 
Dim mSize As Long 
Dim result As String 
Dim RepChars As Variant 

RepChars = Array("a", "b", "c") 

mLBound = LBound(RepChars) 
mUBound = UBound(RepChars) 

result = Range("A2").Value 

For mSize = mLBound To mUBound 
    result = Replace(result, CStr(RepChars(mSize)), "") 
Next 

Range("A3").Value = result 
+0

更好意味着更少的CPU功率和更少的線路。任何方式現在看來只有解決方案。 – Rahul

1

或者可以使用正則表達式。基於this answer的示例。

Option Explicit 

Sub ReplaceWithRegex() 
    Dim strPattern As String 
    Dim strReplace As String 
    Dim regEx As Variant 
    Dim strtxt As String 

    Set regEx = CreateObject("vbscript.regexp") 
    strtxt = "String1.String2.String3.String4.String5.String6.String7.String77" 
    strPattern = "(String.)" ' (String\d+) for replacing e.g. 'String77' etc. 
    strReplace = "" 

    With regEx 
     .Global = True 
     .MultiLine = True 
     .IgnoreCase = False 
     .Pattern = strPattern 
    End With 

    If regEx.Test(strtxt) Then 
     Debug.Print regEx.Replace(strtxt, strReplace) 
    Else 
     MsgBox ("Not matched") 
    End If 
End Sub 

regexr

1

方式一:

Function RemoveTokens(target As String, ParamArray tokens() As Variant) As String 
    Dim i As Long 
    For i = 0 To UBound(tokens) 
     target = Replace$(target, tokens(i), "") 
    Next 
    RemoveTokens = target 
End Function 

?RemoveTokens("AA BB CC DD EE", "BB") 
AA CC DD EE 

?RemoveTokens("AA BB CC DD EE", "BB", "EE", "AA") 
    CC DD 
+0

我覺得SO有一些錯誤。沒有收到這個答案的通知。 – Rahul

相關問題