Text box prompt text in Excel VBA

后端 未结 2 889
说谎
说谎 2021-01-06 18:17

You know how sometimes you see text in an input field prompting for an answer? When you click it, it goes away, but comes back if you deselect without having typed anything.

2条回答
  •  死守一世寂寞
    2021-01-06 18:29

    I think you're referring to a "placeholder" in a UserForm. The two tricks that I use to achieve this are the "tag" property and Enter and Exit events. First, create your sub modules that will fire upon Enter (focus) and Exit (blur).

    Sub TB_enter(TB_name)
        If Len(Me.Controls(TB_name).Tag) = 0 Then
            Me.Controls(TB_name).Tag = Me.Controls(TB_name).Value
            Me.Controls(TB_name).Value = vbNullString
        End If
    End Sub
    Sub TB_exit(TB_name)
        If Len(Me.Controls(TB_name).Value) = 0 Then
            Me.Controls(TB_name).Value = Me.Controls(TB_name).Tag
            Me.Controls(TB_name).Tag = vbNullString
        End If
    End Sub
    

    Next, for each instance of your textbox on your userform, double click on the textbox while in View Object mode. This will automatically create a Private Sub for the change event. Head to the upper right hand corner of the toolbar and change the "Change" drop down list to "Enter". This will create a new Private Sub for the Enter event. Repeat this process again, but select "Exit" to create the Exit event. Now, simply copy the following code into the Enter and Exit events respectively (I've used the default name for the first textbox, but this is name independent when calling the events).

    Private Sub TextBox1_Enter()
        TB_enter ActiveControl.Name
    End Sub
    Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
        TB_exit ActiveControl.Name
    End Sub
    

    If you are placing these calls in an external module, simply replace "Me" with the name of the UserForm.

提交回复
热议问题