Search code examples
excelvbareplaceformatfind

VBA code - find and replace format of a single value


Could someone please help with the find and replacing the format of a single digit, i.e. cell has a value "1,10,11,5", and am I looking to color and change the format of value 11, and want to keep other values intact. Find and replace does work but changes font and size of complete cell instead of just "11".

Range("I2:M14").Select
Selection.Replace What:="11,", Replacement:="11,", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=True

Solution

    • Replacing in Excel with the format doesn not produce the desired results.
    • You need to find the keyword for each cell and change its format.
    • Locating the number 11 within a cell containing 11, is not reliable. For example, if the cell value is 2,111,33,11, it accidentally matches part of 111 and misses the last 11. Changing the keyword to ,11, would be more reliable.
    Option Explicit
    Sub Demo()
        Dim c As Range, sTxt As String, iLoc As Long
        Const KEYWORD = ",11,"
        For Each c In Range("I2:M14")
            sTxt = c.Value
            If Len(sTxt) > 0 Then
                sTxt = "," & sTxt & ","
                iLoc = InStr(sTxt, KEYWORD)
                If iLoc > 0 Then
                    c.Characters(iLoc, Len(KEYWORD) - 2).Font.Color = vbRed
                End If
            End If
        Next
    End Sub