繁体   English   中英

更改单元格中包含特定值的一行文本的字体颜色

[英]Change font color for a row of text in cell which contains a certain value

我正在用 excel 编写一个签入/签出程序,并收到请求,如果一行包含“|0|” 它应该得到不同的字体颜色。

我已经尝试过 Instr 和 Cells().Characters 但我似乎无法弄清楚如何去做。

单元格可以有多种文本行。 这很容易通过在返回时拆分它们并使用 for 循环来解决,但我似乎无法弄清楚如何为包含所需值的一行文本分配不同的字体颜色。

用于说明数据的图像:

在此处输入图像描述

我如何最好地解决这个问题?

补充资料:

这样做的目的是在按钮上按下 |O| 所在的整行文本。 is 会以不同的颜色着色。 没有这个的其他文本行将保持相同的颜色。

就像在这个图像中作为一个概念

[在此处输入图像描述 ]

尝试这个。 这个对我有用。

    Sub ChangeRowFontColour()
    
    Dim rng As Range
    Dim TextToFind As String
    Dim FirstFound As String
    
    TextToFind = "Specific Text"

        With ActiveSheet.UsedRange
            Set rng = .Cells.Find(TextToFind, LookIn:=xlValues)
            
            If Not rng Is Nothing Then
            FirstFound = rng.Address
                Do
                    rng.EntireRow.Font.ColorIndex = 3
                                            
                    For Each part In rng
                        lenOfPart = Len(part)
                        lenTextToFind = Len(TextToFind)
                        For i = 1 To lenOfPart
                            tempStr = Mid(part, i, lenTextToFind)
                            If tempStr = TextToFind Then
                                part.Characters(Start:=i, Length:=lenTextToFind).Font.ColorIndex = 0
                            End If
                        Next i
                    Next
                    
                    Set rng = .FindNext(rng)
                  
                Loop While Not rng Is Nothing And rng.Address <> FirstFound
            End If
        End With
            
End Sub

尝试这个

Public Sub ExampleMainSub()
    Dim cell As Range
    For Each cell In Selection
        If HasMySymbols(cell.Value) Then
            WorkWithCellContent cell
        Else
            cell.Font.ColorIndex = xlAutomatic
            cell.Font.TintAndShade = 0
        End If
    Next cell
End Sub

Private Sub WorkWithCellContent(ByVal cell As Range)
    Dim arr As Variant
    arr = Split(cell.Value, Chr(10))
    
    Dim firstPosOfRow As Long
    firstPosOfRow = 1
    
    Dim subLine As Variant
    For Each subLine In arr
        If HasMySymbols(subLine) Then
            cell.Characters(start:=firstPosOfRow, Length:=Len(subLine)).Font.Color = vbRed
        Else
            cell.Characters(start:=firstPosOfRow, Length:=Len(subLine)).Font.ColorIndex = xlAutomatic
        End If
        firstPosOfRow = firstPosOfRow + Len(subLine) + 1 '+1 is needed
    Next subLine
    
End Sub

Private Function HasMySymbols(ByVal somestring As String) As Boolean
    HasMySymbols = InStr(1, somestring, "|0|") > 0
End Function

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM