删除Microsoft Excel中特定标记之间的文本

我有一些文字是这样的:

Lorem ipsum dolor <code> sit amet,consectetuer adipiscing elit,sed diam nonummy nibh euismod tincidunt ut <code> laoreet dolore magna </ code> aliquam erat volutpat。

我试图删除每一对“代码”标签之间的一切。 我写了一个在每个单元只有一对标签的情况下运行良好的函数,但是它并不考虑多个实例。 这是所需的输出:

Lorem ipsum dolor <code> </ code> sed diam nonummy nibh euismod tincidunt ut <code> </ code> aliquam erat volutpat。

你会如何build议我做?

基于macroslogging器:

Sub Test() 'working for selection replacing all <*> sections Selection.Replace What:="<*>", Replacement:="", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False End Sub 

编辑尝试2后,OP的意见:

 Sub Attempt_second() 'working for selection replacing all <*> sections Selection.Replace What:="<*code>*<*/*code>", Replacement:="<code></code>", LookAt:=xlPart, _ SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _ ReplaceFormat:=False End Sub 

它会将文本replace为<code></code>消除两者之间的额外空间。

这个VBA函数可以用来去除HTML标签的打开和closures以及它们所包含的内容。 它使用正则expression式,这应该是有限的使用(但要小心使用正则expression式parsingHTML )。

 Function stripEnclosed(strIn As String) As String Dim re As VBScript_RegExp_55.RegExp, AllMatches As VBScript_RegExp_55.MatchCollection, M As VBScript_RegExp_55.Match Dim closeIndex As Long tmpstr = strIn Set re = New VBScript_RegExp_55.RegExp re.Global = True re.Pattern = "<[^/>]+>" Set AllMatches = re.Execute(tmpstr) For Each M In AllMatches closeIndex = InStr(tmpstr, Replace(M.Value, "<", "</")) If closeIndex <> 0 Then tmpstr = Left(tmpstr, InStr(tmpstr, M.Value) - 1) & Mid(tmpstr, closeIndex + Len(M.Value) + 1) Next M stripEnclosed = tmpstr End Function 

注意:您必须将“Microsoft VBScript Regular Expressions 5.5”引用添加到您的VBA项目中。

如果您只想删除某个标签(例如<CODE></CODE> ),只需将re.Pattern = "<[^/>]+>"代码行replace为以下内容:

 re.Pattern = "<CODE>" 

KazJaw的回答简单,优雅,似乎满足您的需求。

我采取了一个完全不同的方法:

 Public Function StripHTML(str As String) As String Dim RegEx As Object Set RegEx = CreateObject("vbscript.regexp") With RegEx .Global = True .IgnoreCase = True .MultiLine = True .Pattern = "<[^>]+>" End With StripHTML = RegEx.Replace(str, "") Set RegEx = Nothing End Function