我有两个字符串,如
str1= "[abc 1],[def 2],[ghi 3],[jkl 4],[mno 5]"
str2="[def 2],[mno 5]"
str2 [def 2],[mno 5]中的字符串应删除或替换为""在str1中。结果将是
str1="[abc 1],[ghi 3],[jkl 4]"
我尝试替换功能但没有工作给出完整的字符串str1
strorg1 = Replace(str1, str2,"")
答案 0 :(得分:2)
我认为这是有效的:
Option Explicit
Sub gen()
Dim ReplaceList(1 To 5) As String
Dim str1 As String, strToReplace As Variant
Dim a() As String
Dim element As Long
str1 = "[abc 1],[def 2],[ghi 3],[jkl 4],[mno 5]"
ReplaceList(1) = "[def 2]"
ReplaceList(2) = "[mno 5]"
a = Split(str1, ",")
For element = UBound(a) To 0 Step -1
For Each strToReplace In ReplaceList
If a(element) = strToReplace Then
a(element) = ""
End If
Next
Next
str1 = Join(a)
Debug.Print str1
End Sub
编辑,我无权访问Access,我希望这有效,如果没有,它应该让你在正确的轨道上。
答案 1 :(得分:2)
试试这个(抱歉现在无法格式化代码)
Option Explicit
Sub Main()
Dim str1 As String, str2 As String
Dim str As Variant
str1 = "[abc 1],[def 2],[ghi 3],[jkl 4],[mno 5]"
str2 = "[def 2],[mno 5]"
str1 = "|" & str1 & "|"
For Each str In Split(str2, ",")
str1 = Replace(str1, str, "")
Next str
str1 = Replace(Replace(Replace(str1, ",,", ","), "|,", ""), ",|", "")
MsgBox str1
End Sub
答案 2 :(得分:1)
试试这个:
Sub Macro1()
Dim str1 As String
Dim str2 As String
Dim strTemp As String
Dim strTemp2 As String
Dim strOut As String
str1 = "[abc 1],[def 2],[ghi 3],[jkl 4],[mno 5]"
str2 = "[def 2],[mno 5]"
strOut = str1
Do
strTemp = Application.WorksheetFunction.Search("]", str2)
strTemp2 = Mid(str2, 1, strTemp + 1)
strOut = Replace(strOut, strTemp2, "")
str2 = Replace(str2, strTemp2, "")
Loop Until str2 = ""
End Sub
它将解析你的str2,在[]中剪切片段并逐个从str1中删除它。
使用excel 2010,输出符合您的预期。