How to find and replace part of a cell with formatted text

前端 未结 4 666
北恋
北恋 2021-01-06 09:44

In an Excel 2007 spreadsheet I want to find-replace with highlighting part of the text in a cell. Using find-replace reformats the entire cell though.

For ex

4条回答
  •  独厮守ぢ
    2021-01-06 10:25

    To make the search item case agnostic you can use:

    Sub FormatSelection()
    
    Dim cl As Range
    Dim SearchText As String
    Dim StartPos As Integer
    Dim EndPos As Integer
    Dim TestPos As Integer
    Dim TotalLen As Integer
    
    On Error Resume Next
    Application.DisplayAlerts = False
    SearchText = Application.InputBox _
    (Prompt:="Enter string.", Title:="Which string to format?", Type:=2)
    On Error GoTo 0
    Application.DisplayAlerts = True
    If SearchText = "" Then
    Exit Sub
    Else
    For Each cl In Selection
      TotalLen = Len(SearchText)
      StartPos = InStr(Ucase(cl), Ucase(SearchText))
      TestPos = 0
      Do While StartPos > TestPos
        With cl.Characters(StartPos, TotalLen).Font
          .FontStyle = "Bold"
          .ColorIndex = 3
        End With
        EndPos = StartPos + TotalLen
        TestPos = TestPos + EndPos
        StartPos = InStr(TestPos, cl, SearchText, vbTextCompare)
      Loop
    Next cl
    End If
    End Sub
    

提交回复
热议问题