How to only format a part of a string in a cell wi

2020-04-17 07:37发布

The goal is to change these values A10,B10,C10,D10,E10,F10,G10,H10,I10,J1 to a font blue color.

For example, "Yonge St A10, B10", only A10 and B10 should be in a blue font color, whereas "Yonge St" will remain black.

I have a VBA code. However, the code changes all the text color in a cell, and not the specific text that should be changed. See below:

Dim i As Long
Dim sequences As String

' The sequence contains the values to highlight
sequences = "A10,B10,C10,D10,E10,F10,G10,H10,I10,J1"

' Split sequence list,  so it can loop through each value in the array

Dim seqList() As String
seqList = Split(sequences, ",")

' This loops through up to Row 20 to determine if the cell value contains a sequence value, if it does, then it highlights it blue
For i = 1 To 20
    Dim cellVal As String
    cellVal = Cells(i, 2).Value 'Cells (i, 2) --> i refers to row number and 2 refers to column number. So in this case I set it to B

    For Each seq In seqList
        Dim outcomeNum As Integer
        outcomeNum = InStr(cellVal, seq)

        If outcomeNum > 0 Then
            Cells(i, 2).Font.Color = RGB(0, 0, 255) ' You can set the blue colour here or change it to something else
        End If

        Next seq

    Next i

1条回答
该账号已被封号
2楼-- · 2020-04-17 08:17

You need to specify the character start and length within the cell, that you want to format:

Therefore replace

Cells(i, 2).Font.Color = RGB(0, 0, 255)

with

Cells(i, 2).Characters(Start:=outcomeNum, Length:=Len(seq)).Font.Color = RGB(0, 0, 255)

Just because I noticed: seq is missing in declaration.

Dim seq As Variant

I recommend using Option Explicit to avoid forgetting any declarations and minimizing errors due to typos in variable names.

查看更多
登录 后发表回答