简体   繁体   中英

Remove Substring but Preserve Formatting

I have a small bit of code that will remove the substring junk from cells that I have selected:

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

The code works, but it destroys the formatting of the characters that remain in the cells. So if I start with:

在此输入图像描述

I end up with:

在此输入图像描述



Is there any way to avoid disturbing the formatting of the characters that remain ??

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM