Your main problem is the way you are adding text to your RTB
RichTextBox1.Text = RichTextBox1.Text & vbCrLf & Text1.Text
Text is, well ... just text. It doesn't have any concept of colour, format etc. For example compare NotePad (a text editor) to something like MS Word (a rich text editor)
The next problem is the way you are selecting
.SelLength
.SelLength = Len(RichTextBox1)
Firstly - Are you absolutely sure sure that the default property of this control is its
Text
property?
.SelLength = Len(RichTextBox1.Text)
would have been better, but still wouldn't fix your problem as you are selecting the entire text of the RTB.
You will be better off using the
.SelText
property of the RTB ... set the start point of the selection, set the colour you want, then set the selected text to be the information you want to insert. Like this
Dim start1 As Integer
Dim lCurrColour As Long
start1 = Len(RichTextBox1.Text)
If RichTextBox1.Text <> "" Then
With RichTextBox1
.SelStart = start1
lCurrColour = .SelColor
.SelColor = vbGreen
.SelText = vbCrLf & Text1.Text
.SelColor = lCurrColour
End With
Else
...etc
Notice that I capture the current colour at the point I'm going to insert the line -
lCurrColour
and then set it back after the insert.
If this was me I would refactor the code to avoid duplication of code/effort. I have a personal preference for an
if
statement being as close as possible to the thing that is affected by it (NB - personal preference - that's just me, others might disagree). I would have done something more like this
Dim lCurrColour As Long
With RichTextBox1
.SelColor = IIf(RichTextBox1.Text = "", 255, vbGreen)
lCurrColour = .SelColor
.SelStart = Len(RichTextBox1.Text)
.SelText = Text1.Text & vbCrLf
.SelColor = lCurrColour
End With