首页 > 解决方案 > VBA占位符文本仅在键入时消失,而不是在 UserFrom 上输入文本框时消失

问题描述

' 我正在寻找创建占位符文本(重影文本)以帮助用户知道在该字段中输入什么,但我希望它的行为与在线表单非常相似,其中占位符文本在输入文本框时不会消失,但是仅当您在其中输入新文本时才会消失。

' 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

标签: excelvbaplaceholder

解决方案


这是我的做法:

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

在此处输入图像描述


推荐阅读