Domanda

I'm looking for a way to display every letter in a TextBox within a UserForm in different colors using VBA. For example first character red,second blue,third... . Is there any way to do this?

È stato utile?

Soluzione

This is not possible using TextBox Control.
If you are using Excel 2010 or higher however, you can use InkEdit Control.
It is an additional control under Tools > Additional Controls (Excel VBE).

enter image description here

Once you've added it, it will be available in your Toolbox as seen below.

enter image description here

You can then use it as another Control in your UserForm.
To know more about what you can do with an InkEdit Control, check MSDN.
Btw, here is a sample code which colors the entry(per Char) based on its position as you type.

Private Sub InkEdit1_Change()

Dim i As Long

If Me.InkEdit1.Text <> "" Then
    For i = 1 To Len(Me.InkEdit1.Text)
        Me.InkEdit1.SelStart = i - 1 '~~> identifies the start of selection
        Me.InkEdit1.SelLength = 1 '~~> identifies the length of selection
        Select Case i
        Case 1: Me.InkEdit1.SelColor = RGB(255, 0, 0) '~~> colors 1st char Red
        Case 2: Me.InkEdit1.SelColor = RGB(0, 255, 0) '~~> colors 2nd char Green
        Case 3: Me.InkEdit1.SelColor = RGB(0, 0, 255) '~~> colors 3rd char Blue
        Case 4: Me.InkEdit1.SelColor = RGB(255, 255, 0) '~~> colors 4th char Yellow
        Case 5: Me.InkEdit1.SelColor = RGB(255, 0, 255) '~~> colors 5th char Indigo
        End Select
        Me.InkEdit1.SelStart = i '~~> this puts the cursor to end
    Next
End If

End Sub

For the above sample, I limit the number of characters entered in the control to 5.
InkEdit both accepts RGB and Color Index but I'm comfortable in using RGB.
Your question is lacking details so I cannot provide more; just hopes that this helps you a bit.
If ever, your version of Excel is not 2010, I think there's an equivalent control for lower versions as well.

Result:
enter image description here

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top