Text box prompt text in Excel VBA

后端 未结 2 892
说谎
说谎 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:36

    You could do it with a couple of events. To clear the box on click is pretty easy:

    Private Sub TextBox1_GotFocus()
        TextBox1.Text = ""
    End Sub
    

    I'd add some other steps, add a worksheet_activate event to set an inital value and set a flag for if the default value is set:

    Private Sub Worksheet_Activate()
        Dim textBox1Default As Boolean
        TextBox1.Text = "Please enter some text here"
        textBox1Default = True
    End Sub
    

    Then I'd add a TextBox1_Change event to remove the default flag

    Private Sub TextBox1_Change()
        If textBox1Default = True Then textBox1Default = False
    End Sub
    

    And finally adjust the original GotFocus event to include the flag check:

    Private Sub TextBox1_GotFocus()
        If textBox1Default Then TextBox1.Text = ""
    End Sub
    

    You'll need to make it work for you, this way if you change tabs it will reset the text but you can have it check that on activate and change it to suit when you want it to reset.

    Jesse

提交回复
热议问题