VBA占位符文本仅在键入时消失,而在UserFrom上输入文本框时则不消失

时间:2019-07-14 18:07:59

标签: excel vba placeholder

'我正在尝试创建占位符文本(重影文本)以帮助用户了解在该字段中键入的内容,但是我希望它的行为与在线表单非常相似,在该表单中,占位符文本在输入时不会消失文本框,但只有在其中输入新文本时才会消失。

' 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

1 个答案:

答案 0 :(得分:1)

这是我要怎么做:

Private Sub Label1_Click()
    TextBox1.SetFocus
End Sub

Private Sub TextBox1_Change()
   Label1.Visible = Len(TextBox1.Text) = 0
End Sub

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    Label1.Visible = Len(TextBox1.Text) = 0
End Sub

Private Sub UserForm_Initialize()
    With Label1
        .SpecialEffect = fmSpecialEffectSunken
        .BackColor = vbGrayText
        .Caption = "    Name"
    End With
End Sub

enter image description here