how do i make the richtextbox show different colors for different text, like the VB Editor???? The editor shows different colors for different type of text
Printable View
how do i make the richtextbox show different colors for different text, like the VB Editor???? The editor shows different colors for different type of text
Try this code. Make a form with a RichTextBox on it and insert this code into the Form.
The sub called HighlightText will change the colours for specific words. The basic syntax for it is...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 Form_Resize()
RichTextBox1.Move 0, 0, ScaleWidth, ScaleHeight
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. The basic syntax is as follows
' HighlightText MyWord, MyColour
HighlightText "if", vbBlue
HighlightText "then", vbBlue
HighlightText "else", vbBlue
HighlightText "end", vbBlue
HighlightText "print", vbBlue
HighlightText "do", vbBlue
HighlightText "loop", vbBlue
End Sub
HightlightText "MyWord", MyColour