Results 1 to 4 of 4

Thread: another richtextbox question

  1. #1
    Guest

    Unhappy

    I have been familiarising myself with the richtextbox so that I can use it in the future. What I've been trying to do is have to text of the box updated by code, but with different colours but I can't seem to get it right.

    Whenever I add text to the box, it is like the formatting set for the previous text is lost (while stepping through the code, the previous formatting the lost when the new text is added). Here is the code I am using:

    Code:
    Option Explicit
    Private Const msg = "123"
    
    Private Sub Command1_Click()
        rtb.Text = rtb.Text & msg
        rtb.SelStart = Len(rtb.Text) - Len(msg)
        rtb.SelLength = Len(msg)
        rtb.SelBold = True
        rtb.SelLength = 0
    End Sub
    
    Private Sub Command2_Click()
        rtb.Text = rtb.Text & msg
        rtb.SelStart = Len(rtb.Text) - Len(msg)
        rtb.SelLength = Len(msg)
        rtb.SelBold = False
        rtb.SelLength = 0
    End Sub
    Thanks,
    Sunny

  2. #2
    Addicted Member
    Join Date
    Sep 2000
    Posts
    138
    Here is an analysis:
    Code:
    Option Explicit
    
    Dim lngMsgLen As Long
    Private Const msg = "123"
    
    Private Sub Command1_Click()
        '
        'Your problem originates from the line "rtb.Text = rtb.Text & msg"
        'because every time you click on the command button the RichTextBox
        'is assigned a new value. When the new value is assigned, it
        'contains only the text itself but not the format. In order to obtain
        'your specific effect, you can use the following code. But if you
        'want to define formats at random, it seems that you have to use a
        'two dimention array to note down the positions and lengths.
        
        lngMsgLen = lngMsgLen + Len(msg)
        rtb.Text = rtb.Text & msg
        rtb.SelStart = Len(rtb.Text) - lngMsgLen
        rtb.SelLength = lngMsgLen
        rtb.SelBold = True
        rtb.SelLength = 0
        
    End Sub

  3. #3
    Guest
    Thanks for the reply. I've also found another way, though shorter.

    Code:
    Option Explicit
    Private Const Msg = "123"
    
    Private Sub Command1_Click()
        rtb.SelBold = True
        rtb.SelColor = vbBlue
        rtb.SelText = Msg
    End Sub

    Sunny

  4. #4
    Addicted Member
    Join Date
    Sep 2000
    Posts
    138
    Wow, that's much better, Sunnyl.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width