Different colour in one textbox

manish_v
manish_v used Ask the Experts™
on
how can we write different colour in one textbox
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Firstly you need to use a Richtextbox.  Put a rich text box on the form and add this code to the general declarations.   It takes a RichTextBox, a String and a Color as its parameters.

Private Sub Form_Load()
RichTextBox1.Text = "This is my text"
ChangeTextColor RichTextBox1, "is", vbRed
End Sub

Private Sub ChangeTextColor(MyRichText As RichTextBox, MyString As String, TextColor As Long)
Dim i As Integer
Dim SelStart As Integer
Dim SelLen As Integer
Dim ReturnSelStart As Integer
Dim ReturnSelLen As Integer
ReturnSelStart = MyRichText.SelStart
ReturnSelLen = MyRichText.SelLength
SelLen = Len(MyString)
   For i = 1 To Len(MyRichText.Text)
       SelStart = InStr(i, MyRichText.Text, MyString)
       If SelStart <> 0 Then
           MyRichText.SelStart = SelStart - 1
           MyRichText.SelLength = SelLen
           MyRichText.SelColor = TextColor
       Else
           Exit For
       End If
       i = i + SelLen
   Next i
MyRichText.SelStart = ReturnSelStart
MyRichText.SelLength = ReturnSelLen
   
End Sub

Commented:
Here is an example:

' set textbox 1 background to green and
' textbox foreground to blue

text1.BackColor = vbGreen
text1.ForeColor = vbBlue

The text will be blue with a green background for this textbox.

hope this helps.

Author of the Year 2009

Commented:
Hi manish_v,
It appears that you have forgotten this question. I will ask Community Support to close it unless you finalize it within 7 days. I will ask a Community Support Moderator to:

    Accept TDC_LuCiFeR's comment(s) as an answer.

manish_v, if you think your question was not answered at all or if you need help, just post a new comment here; Community Support will help you.  DO NOT accept THIS comment as an answer.

EXPERTS: If you disagree with that recommendation, please post an explanatory comment.
==========
DanRollins -- EE database cleanup volunteer

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial