0
votes

I am trying to figure out how to get a textbox in an excel userform to update like an HTML textbox. For instance, if you have a default value set to "First Name" and you click in that textbox, it will disappear and let you type in. Once you click out, if you didn't type anything, it will go back to the default "First Name".

I have found quite a few asking about this same type of thing, but none are working for me. Here is my code so far.

Sub QCToolsForm()
QCTools.Show vbModeless
End Sub

Private Sub RUBSTotalExpense_Enter()
Debug.Print "Enter"
If Me.RUBSTotalExpense.Value = "Total Expense" Then
    Me.RUBSTotalExpense.Value = ""
End If
End Sub

Private Sub RUBSTotalExpense_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Debug.Print "Exit"
If Me.RUBSTotalExpense.Value = "" Then
    Me.RUBSTotalExpense.Value = "Total Expense"
End If
End Sub

Private Sub UserForm_Initialize()
updateDefault

End Sub

Public Function updateDefault()

If Me.RUBSTotalExpense.Value = "" Then
    Me.RUBSTotalExpense.Value = "Total Expense"
End If

End Function

The exit sub is not running until I close the userform. I have also tried lose and getfocus with no luck with those at all. I have also tried before and afterupdate, but they only work the first time. I want it to disappear every time you click in the box if the value is "Total Expense". How do I get the exit sub or something similar to run when I leave the textbox?

Userform

1

1 Answers

1
votes

I tried using your code for Enter and Exit and it worked for me with a test userform. It's updating the field correctly, and printing "Enter" when you select the textbox and "Exit" when you select something else on the userform. Note that for Exit to trigger you need to give focus to something else on the userform. Simply clicking elsewhere will not take focus from the textbox, you must click on another textbox or other control.

I suggest using Debug.Print to observe exactly when each method you try is being called, so that you can be sure when your code is running.

Private Sub TextBox1_Enter()
    Debug.Print "Enter"
    If TextBox1.Value = "Total Expense" Then
        TextBox1.Value = ""
    End If
End Sub

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    Debug.Print "Exit"
    If TextBox1.Value = "" Then
        TextBox1.Value = "Total Expense"
    End If
End Sub