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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30567552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 09:38:07  来源:igfitidea点击:

Change font color for a part of text in cell

excelvba

提问by Vignesh Subramanian

I have cells which will contain the below value

我有包含以下值的单元格

"Image not allowed|png"

I want to change the color of |pngalone 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?

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

回答by R3uK

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

回答by Joe

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.

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

回答by 0m3r

Is it possible to change only the selected text color

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

Simple

简单的

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