Partial text color for multiple phrases in a cell

2019-08-19 06:37发布

I have a list of user generated tags, let's say country names like: Argentina, Brazil, France, Germany, Great Britain etc. And I want assign color for these tags as they are selected from a dropdown list in a column. Some cells will have multiple tags. For each unique tag, I want to specify a unique color.

Cell A1: France (in blue)
Cell A2: France (in blue), Brazil (in green)

I have tried several ways to assign color but all ended up styling the whole cell. Is it doable?

edit: I can do the tagging part. The unique color for tags is a problem.

标签: excel vba
1条回答
Viruses.
2楼-- · 2019-08-19 07:23

So as I commented, you have to go through the cell's characters and color them individually. Here is an example on your mock-up sample data:

enter image description here

Sub ColorTag()

Dim Tags() As String, Tag As Long, X As Long, Y As Long, ClrIndex As Long, ChrPos As Long
With ThisWorkbook.Sheets("Sheet1")
    For X = 1 To .Cells(.Rows.Count, "A").End(xlUp).Row
        Tags() = Split(.Cells(X, 1), ",")
        For Tag = LBound(Tags) To UBound(Tags)
            If Tags(Tag) = "France" Then
                ClrIndex = 5
            ElseIf Tags(Tag) = "Brazil" Then
                ClrIndex = 4
            End If
            Y = InStr(1, .Cells(X, 1), Tags(Tag))
            For ChrPos = Y To Y + Len(Tags(Tag) - 1)
                .Cells(X, 1).Characters(ChrPos, 1).Font.ColorIndex = ClrIndex
            Next ChrPos
        Next Tag
    Next X
End With

End Sub

Result:

enter image description here

ColorIndex codes from here

查看更多
登录 后发表回答