将变量的字体颜色更改为单元格中文本的一部分

use*_*242 5 excel vba excel-vba

我正在努力使用VBA宏,它应该为文本的一部分着色.

宏看起来像

Sub Note()
        Dim c As Range
        Dim val As String
        Set c = ActiveCell
        val = InputBox("Add note", "Note text")
            If IsEmpty(c.Value) = True Then
                c.Value = Format(Now(), "DD MMM YY Hh:Nn") & ": " & val
            Else
                c.Value = c.Value & Chr(10) & Format(Now(), "DD MMM YY Hh:Nn") & ": " & val
        End If
        End Sub
Run Code Online (Sandbox Code Playgroud)

我希望实现Now()将为红色,其余文本将为绿色.

我试着玩.Font.Color = vbRed等,但没有任何运气

我也看看这个答案,但它不是我想要的

R3u*_*3uK 2

您链接了一个答案,但您没有使用其中的内容,为什么?

尝试这个 :

Sub Note()
Dim c As Range
Dim val As String
Dim StartChar As Integer, _
    LenColor As Integer
Set c = ActiveCell

val = InputBox("Add note", "Note text")

With c
    .Font.Color = RGB(0, 0, 0)
    If IsEmpty(.Value) = True Then
        StartChar = 1
        LenColor = Len("DD MMM YY Hh:Nn")
        .Value = Format(Now(), "DD MMM YY Hh:Nn") & ": " & val
        .Characters(Start:=StartChar, Length:=LenColor).Font.Color = RGB(255, 0, 0)
    Else
        StartChar = Len(.Value) + 1
        LenColor = Len("DD MMM YY Hh:Nn")
        .Value = .Value & Chr(10) & Format(Now(), "DD MMM YY Hh:Nn") & ": " & val
        .Characters(Start:=StartChar, Length:=LenColor).Font.Color = RGB(255, 0, 0)
    End If
End With 'c
End Sub
Run Code Online (Sandbox Code Playgroud)