2013-06-04 29 views
2

删除特定的标记之间的文本,我有一些文字是这样的:在Microsoft Excel

Lorem ipsum dolor <code>sit amet, consectetuer adipiscing elit,</code> 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.

你会建议我怎么做?

+0

你的意思是你想删除之间的一切“代码“标签? – gtr1971

+0

是的,这正是我想要做的。 – user1029296

+0

你想要的输出是什么?请将其添加到您的帖子。 – Excellll

回答

0

基于宏录制:

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 

它将取代文本<code></code>之间消除额外的空间。

+0

的OP想删除包含在HTML标签以及文本。这并不是那样做的。 – Excellll

+1

@Excellll,你有你失望,投票之前试过这种?从'Lorem ipsum dolor < code>坐amet'你会得到'Lorem ipsum dolor sit amet'-是不是正确?我错过了什么(或你)? –

+0

仔细看看OP的预期输出。所有打开和关闭标签之间的文本也应该删除。 – Excellll

0

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 
+1

OP想要删除HTML标签中包含的文本。这并不是那样做的。 – Excellll

1

这VBA函数可以用来去掉打开和关闭的HTML标签,他们包围了什么。它使用正则表达式,这应该是在这个有限的使用(但beware using regex to parse HTML)确定。

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 

注意:你必须在“微软的VBScript正则表达式5.5”引用添加到您的VBA项目。

如果你只是想删除某个标签(例如<CODE></CODE>)只是下文取代re.Pattern = "<[^/>]+>"行的代码:

re.Pattern = "<CODE>" 
+1

它太复杂了,在这种情况下不需要! –