【发布时间】:2026-02-03 15:15:02
【问题描述】:
' 我正在寻找创建占位符文本(重影文本)以帮助用户知道在该字段中输入什么,但我希望它的行为与在线表单非常相似,其中占位符文本在输入时不会消失文本框,但仅当您在其中输入新文本时才会消失。
' enterfieldbehavior is set to 1 - fmEnterFieldBehaviorRecallSelection in properties to avoid selecting placeholder text
Private Sub userform_initialize()
TextBox2.Value = "Name" 'upon starting UserForm, the placeholder text is launched in the textbox
TextBox2.ForeColor = &H8000000C 'grey
End Sub
Private Sub TextBox2_Enter()
If TextBox2.Text <> "Name" Then
TextBox2.SelStart = TextBox2.SelLength 'Upon entering the textbox, the cursor is placed only at the start and not the middle or end of the placeholder text
Else
' I need the oppositie of the above, to put the cursor at the end of text as the placeholder text is gone
End If
End Sub
Private Sub TextBox2_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
TextBox2.SelStart = TextBox2.SelLength ' If a user uses the mouse to enter the textbox
End Sub
Private Sub TextBox2_Change()
If TextBox2.Text <> "Name" Then
TextBox2.Text = ""
TextBox2.ForeColor = &H8000000C 'grey
Else
TextBox2.Value = TextBox2.Value ' This is where I'm lost as I want to earse the holder text, and let the user type whatever they want
TextBox2.ForeColor = vbBlack
End If
End Sub
Private Sub TextBox2_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If TextBox2.Text = "" Then
TextBox2.Text = "Name" ' If there are no changes to the textbox, replace the placeholder text
TextBox2.ForeColor = &H8000000C 'grey
Else
End If
End Sub
【问题讨论】:
-
如果文本为空或等于“姓名”,则设置文本=“姓名”,颜色为灰色。否则,只需将颜色设置为黑色(文本将由控件本身设置)。
标签: excel vba placeholder