Changer la couleur de la police pour la variable dans le text dans la cellule

Je suis en difficulté avec la macro VBA qui devrait colorier une partie du text.

La macro ressemble à

Sub Note() Dim c As Range Dim val As Ssortingng 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 

Et je veux le réaliser maintenant () sera rouge et le rest du text sera vert.

J'ai essayé de jouer avec .Font.Color = vbRed etc, mais sans chance

Je regarde aussi cette réponse, mais ce n'est pas tout à fait ce que je voulais

Vous avez lié une réponse mais vous n'utilisiez pas ce qui s'y trouvait, pourquoi?

Essaye ça :

 Sub Note() Dim c As Range Dim val As Ssortingng 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 

Essayez comme ceci:

 Option Explicit Sub Note() Dim c As Range Dim val As Ssortingng: val = "vit" Dim lngLen As Long Set c = ActiveCell c.Value = Format(Now(), "DD MMM YY Hh:Nn") & ": " & val lngLen = Len(Format(Now(), "DD MMM YY Hh:Nn")) c.Characters(Start:=1, Length:=lngLen).Font.Color = vbRed End Sub 

J'ai supprimé la boîte de saisie, mais vous pouvez la renvoyer facilement. Il donne probablement ce que vous voulez. Beaucoup de choses, il request la longueur du format Now () et il colorise les premiers N signes dans la formule en rouge, en suivant la logique de la question que vous avez mentionnée dans votre question.

Essaye ça:

 Sub Note() Dim c As Range Dim val As Ssortingng Dim lngPos As Integer Set c = ActiveCell val = InputBox("Add note", "Note text") c.Value = "" If IsEmpty(c.Value) = True Then c.Value = Format(Now(), "DD MMM YY Hh:Nn") & " - " & val lngPos = InStr(ActiveCell.Value, " - ") With ActiveCell.Font .ColorIndex = 4 End With With ActiveCell.Characters(Start:=1, Length:=lngPos - 1).Font .ColorIndex = 3 'or .Color = RGB(255, 0, 0) End With Else c.Value = c.Value & Chr(10) & Format(Now(), "DD MMM YY Hh:Nn") & " - " & val lngPos = InStr(ActiveCell.Value, " - ") With ActiveCell.Font .ColorIndex = 4 End With With ActiveCell.Characters(Start:=1, Length:=lngPos - 1).Font .ColorIndex = 3 'or .Color = RGB(255, 0, 0) End With End If End Sub