更改单元格中部分文本的字体颜色

时间:2021-08-17 22:14:59

I have cells which will contain the below value

我有包含以下值的单元格

"Image not allowed|png"

I want to change the color of |png alone or whatever comes after "|"

我想单独更改| png的颜色或“|”之后的任何颜色

Now i am trying to change the font color using the below code

现在我想使用下面的代码更改字体颜色

Cells(4,2).Font.Color = RGB(255, 50, 25)

It will change the entire cells font color, Is it possible to change only the selected text color(|png) using VBA?

它将改变整个单元格的字体颜色,是否可以使用VBA仅更改所选的文本颜色(| png)?

3 个解决方案

#1


8  

This should be a good start :

这应该是一个好的开始:

Sub vignesh()
Dim StartChar As Integer, _
    LenColor As Integer

For i = 1 To 5
    With Sheets("Sheet1").Cells(i, 1)
        StartChar = InStr(1, .Value, "|")
        If StartChar <> 0 Then
            LenColor = Len(.Value) - StartChar + 1
            .Characters(Start:=StartChar, Length:=LenColor).Font.Color = RGB(255, 0, 0)
        End If
    End With
Next i

End Sub

#2


4  

Yes this is possible. A good way to explore the Excel object model is to use the macro recorder to record a macro where you manually carry out the manipulation you're interested in.

是的,这是可能的。探索Excel对象模型的一个好方法是使用宏录制器录制宏,您可以手动执行您感兴趣的操作。

In this case, you can use:

在这种情况下,您可以使用:

Cell.Characters(Start:=1, Length:=5).Font

to set font properties of a substring in a cell.

设置单元格中子字符串的字体属性。

#3


0  

Is it possible to change only the selected text color

是否可以仅更改选定的文本颜色

Simple

简单

Option Explicit
Sub Test()
    With Selection.Font
        .ColorIndex = 3 
    End With
End Sub

#1


8  

This should be a good start :

这应该是一个好的开始:

Sub vignesh()
Dim StartChar As Integer, _
    LenColor As Integer

For i = 1 To 5
    With Sheets("Sheet1").Cells(i, 1)
        StartChar = InStr(1, .Value, "|")
        If StartChar <> 0 Then
            LenColor = Len(.Value) - StartChar + 1
            .Characters(Start:=StartChar, Length:=LenColor).Font.Color = RGB(255, 0, 0)
        End If
    End With
Next i

End Sub

#2


4  

Yes this is possible. A good way to explore the Excel object model is to use the macro recorder to record a macro where you manually carry out the manipulation you're interested in.

是的,这是可能的。探索Excel对象模型的一个好方法是使用宏录制器录制宏,您可以手动执行您感兴趣的操作。

In this case, you can use:

在这种情况下,您可以使用:

Cell.Characters(Start:=1, Length:=5).Font

to set font properties of a substring in a cell.

设置单元格中子字符串的字体属性。

#3


0  

Is it possible to change only the selected text color

是否可以仅更改选定的文本颜色

Simple

简单

Option Explicit
Sub Test()
    With Selection.Font
        .ColorIndex = 3 
    End With
End Sub