Excel VBA Formating lost on inserting characters

◇◆丶佛笑我妖孽 提交于 2019-12-31 03:59:26

问题


I have the following code which handles a double click event on one of my columns. Basically its a Notes Column so when the user double clicks it... it pops up an input and prompts for the note. The VBA code then appends a date and inserts it into the cell. I wanted the Dates to be in Bold.

However when I first enter a comment the cell is correct. Like this

23/08/2013: Hi there

when I double click the cell again and enter 'Hi again' the whole cell goes bold

23/08/2013: Hi there

23/08/2013: Hi again

I think this is because I am resetting the entire cell text and not appending to the orginal text.. hence losing the orginal formatting.

Can anyone shed any ideas on this. The only way I reckoned I could get it to work would be to look through and find the ctrl(10) char and format it that way but its way over the top.

regards D

Option Explicit

Const STATUS_COL As Integer = 10
Const NOTES_COL As Integer = 13

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim newVal As String
Dim strNote As String
Dim lngPos As Long

If Target.Count > 1 Then GoTo exitHandler

Application.EnableEvents = False

On Error Resume Next

 If Target.Column = NOTES_COL Then 'Add a note
    lngPos = Len(Target.Value)

    strNote = InputBox(Prompt:="Enter Note", _
      Title:="Notes", Default:="")

    If (Len(Trim(strNote)) > 0) Then
        If Target.Value = "" Then
          newVal = Date & ": " & strNote
        Else
          newVal = Target.Value + Chr(10) & Date & ": " & strNote
        End If
        Target.Value = newVal     'set the new value

        Target.Characters(Start:=lngPos + 1, Length:=11).Font.Bold = True
    End If
End If

exitHandler:
  Application.EnableEvents = True
End Sub

回答1:


Sub tester()
    AddNote ActiveSheet.Range("A1"), "hello"
    AddNote ActiveSheet.Range("A1"), "world"
End Sub


Sub AddNote(rng As Range, txt As String)
    Dim l As Long, s As String
    l = Len(rng.Value)
    s = IIf(l > 0, Chr(10), "") & Format(Date, "mm/dd/yyyy") & ": " & txt
    rng.Characters(l + 1, Len(s)).Text = s
    rng.Characters(l + 1, 11).Font.Bold = True
End Sub


来源:https://stackoverflow.com/questions/18448983/excel-vba-formating-lost-on-inserting-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!