2013-06-04 31 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

它太複雜了,在這種情況下不需要! –