簡體   English   中英

將變量的字體顏色更改為單元格中文本的一部分

[英]Change font color for variable as part of text in cell

我正在努力使用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等,但沒有任何運氣

我也看看這個答案,但它不是我想要的

試試這樣:

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個符號用紅色着色。

你聯系了一個答案,但你沒有使用那里的內容,為什么?

試試這個 :

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

嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM