2015-04-04 109 views
4

我有一小段代碼將從細胞去除串垃圾,我選擇了:刪除子串,但保留格式

Sub RemoveJunk() 
    Dim r As Range 
    For Each r In Selection 
     r.Value = Replace(r.Value, "junk", "") 
    Next r 
End Sub 

代碼工作,但它破壞了人物的格式化方法,留在細胞中。所以,如果我開始:

enter image description here

我結束了:

enter image description here



有什麼辦法,以避免干擾仍然存在的字符格式?

回答

5
Sub RemovePreserveFormatting(ByVal Where As Range, Expression As String, Optional ByVal Compare As VbCompareMethod = VbCompareMethod.vbBinaryCompare) 
    Dim c As Range 

    For Each c In Where 
    Dim pos As Long: pos = 0 

    Do 
     pos = InStr(pos + 1, c.Value, Expression, Compare) 
     If pos = 0 Then Exit Do 

     c.Characters(pos, Len(Expression)).Delete 
    Loop 
    Next 

End Sub 
+0

完美! ..............非常感謝你! – 2015-04-04 14:10:05

+0

GSerg,任何解釋句子的機會? – 2015-04-05 07:46:57

+0

@TobyAllen嗯,這是很自我解釋 - 你找到單元格的「價值」字符串的位置,並操縱相應的[字符範圍](http://stackoverflow.com/a/11331709/11683),因爲這就是你在Excel中保留字符級格式。 – GSerg 2015-04-05 10:34:17