سؤال

I have a textbox on a userform. When the userform displays, the textbox opens with some default value.

I want it to be such that the Line1 (or some words) of the default message is displayed in grey color and must be locked for editing. Is it possible?

هل كانت مفيدة؟

المحلول

Locking the TextBox for Editing?

Yes. it is possible.

Just set the .Locked Property to True

Locking/Coloring just the first line or part of a text in textBox?

No. It is not possible in VBA. For partial coloring, you may want to use RichTextBox in lieu of TextBox but then again you will not be able to partially lock the control.

Edit

Alternative: Since the first line of text contains text that shouldn't be edited then why not show that info in a ToolTip using the .ControlTipText property of the TextBox or say a Label which displays when you hover the mouse on top of the TextBox?

For example (Using the .ControlTipText property)

Option Explicit

'~~> This is what goes in the tooltip. Amend as applicable.
Const sMsg As String = "Hello World! This is an example of tooltip text"

Private Sub UserForm_Initialize()
    Dim sSample As String
    Dim i As Long

    For i = 1 To 10
        sSample = sSample & "Blah Blah" & i & vbNewLine
    Next i

    TextBox1.Text = sSample

    '~~> Set to starting point
    TextBox1.SelStart = 0
End Sub

Private Sub TextBox1_MouseMove(ByVal Button As Integer, _
                               ByVal Shift As Integer, _
                               ByVal X As Single, _
                               ByVal Y As Single)
    TextBox1.ControlTipText = sMsg
End Sub

And now when you hover the text on top of the TextBox, you will be shown the ToolTip

enter image description here

نصائح أخرى

This is more a workaround than a solution, but it works perfect (atleast on my computer).

Const defaultLine As String = "YourText" & vbcrlf

Private Sub TextBox1_Change()
    Static oldValue As String

    'set oldValue if empty
    If oldValue = "" Then
        oldValue = defaultLine
    End If

    'disable the change of the first line
    If Left(TextBox1.Value, Len(defaultLine)) <> defaultLine Then
        TextBox1.Value = oldValue
    Else
        oldValue = TextBox1.Value
    End If
End Sub

Private Sub UserForm_Initialize()
    TextBox1.Value = defaultLine
End Sub
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top