删除子字符串但保留格式

时间:2015-04-04 13:41:29

标签: excel vba excel-vba

我有一小段代码会从我选择的单元格中删除子字符串 junk

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


有没有办法避免干扰仍然存在的字符格式?

1 个答案:

答案 0 :(得分: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