简体   繁体   中英

Partial text color for multiple phrases in a cell when phrases are added by data validation [Excel-VBA]

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.

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:

在此处输入图片说明

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:

在此处输入图片说明

ColorIndex codes from here

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