is there a way to make only certain words in a textbox, a different color than the rest?
Printable View
is there a way to make only certain words in a textbox, a different color than the rest?
ony if you use a RichTextBox
ok, if im using a rich text box, how would i do it?
'I personally haven't really played with this
'it's code that I found and put away for a rainy day
[code]
'change the color of text in a RichTextBox
Sub PrintMessage(MessageText As String, MessageColor As Long, RTFBox As RichTextBox)
RTFBox.SelStart = Len(RTFBox.Text)
RTFBox.SelText = MessageText
RTFBox.SelStart = RTFBox.SelStart - Len(MessageText)
RTFBox.SelLength = Len(MessageText)
RTFBox.SelColor = MessageColor
RTFBox.SelStart = Len(RTFBox.Text)
End Sub
' <<<<<<< event code >>>>>>
PrintMessage "This is a sample message in RED." & vbCrLf, RGB(255, 0, 0), RichTextBox1
If you want a multicolored line use like this:
PrintMessage "Green part ", RGB(0, 255, 0), RichTextBox1
PrintMessage "Blue part" & vbCrLf, RGB(0, 0, 255), RichTextBox1
Note you put vbCrLf only when you want to end the line.
Of course, you can use QBColor instead of RGB, or system color constants, or the color hex value.
[code]
Try this.
Code:Option Explicit
Private Sub HighlightText(sKeyword As String, iColour As Long)
Dim nStart As Integer, sPrevChar As String, sNextChar As String
nStart = InStr(1, LCase(RichTextBox1.Text), sKeyword)
Do While nStart <> 0
If nStart > 1 Then
sPrevChar = Mid$(RichTextBox1.Text, nStart - 1, 1)
Else
sPrevChar = " "
End If
If Len(RichTextBox1.Text) >= nStart + Len(sKeyword) Then
sNextChar = Mid$(RichTextBox1.Text, nStart + Len(sKeyword), 1)
Else
sNextChar = " "
End If
If (sPrevChar = Chr(32) Or sPrevChar = Chr(13) Or _
sPrevChar = Chr(10) Or sPrevChar = Chr(9)) And _
(sNextChar = Chr(32) Or sNextChar = Chr(13) Or _
sNextChar = Chr(10) Or sNextChar = Chr(9)) Then
With RichTextBox1
.SelStart = nStart - 1
.SelLength = Len(sKeyword)
.SelColor = iColour
.SelText = UCase(sKeyword)
.SelStart = Len(RichTextBox1.Text)
.SelColor = vbBlack
End With
End If
nStart = InStr(nStart + Len(sKeyword), LCase(RichTextBox1.Text), sKeyword)
Loop
End Sub
Private Sub RichTextBox1_Change()
With RichTextBox1
.SelStart = 0
.SelLength = Len(.Text)
.SelColor = vbBlack
.SelStart = Len(.Text)
End With
' Add more custom words here
HighlightText "blue", vbBlue
HighlightText "yellow", vbYellow
HighlightText "red", vbRed
HighlightText "magenta", vbMagenta
HighlightText "green", vbGreen
End Sub