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

nfg76nw0  于 2023-05-19  发布在  其他
关注(0)|答案(3)|浏览(141)

我正在努力与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

我想实现Now()将是红色的,其余的文本将是绿色的。
我试着玩.Font.Color = vbRed等,但没有任何运气
我也看this answer,但它不完全是我想要的

vof42yt1

vof42yt11#

试试这样:

Option Explicit

Sub Note()

    Dim c           As Range
    Dim val         As String: 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

我已经删除了输入框,但你可以很容易地返回。它可能给出了你想要的内容。它要求的是Now()格式的长度,并按照你在问题中提到的问题的逻辑,将公式中的前N个符号涂成红色。

nkoocmlb

nkoocmlb2#

你连接了一个答案但你没有用里面的内容,为什么?
试试这个:

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
fjnneemd

fjnneemd3#

试试这个:

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

相关问题