Search code examples
vbams-worduserform

Word VBA: Target multiple text input fields and change Value on _Enter() and _AfterUpdate()


I am working with the Office365 version of Word. I have a VBA user form that I've created that contains text boxes with helper text as their intial value. I'm using code as below to clear out the values on user entry into the text field and repopulating the helper text if they leave the field empty:

Private Sub txtCount_Enter() 
'When the user enters the field, the value is wiped out
  With txtCount
    If .Text = "Count No" Then
      .ForeColor = &H80000008
      .Text = ""
    End If
  End With
End Sub

Private Sub txtCount_AfterUpdate() 
'If the user exits the field without entering a value, re-populate the default text
  With txtCount
    If .Text = "" Then
        .ForeColor = &HC0C0C0
        .Text = "Count No"
    End If
  End With
End Sub

My form has a dozen or so of these fields. I know I can somehow access a collection of Text Boxes in the form, but can I then call an action on them? Could someone provide me with an example if this is possible?


Solution

  • My other answer was focused on looping through all controls. To switch the default text, by textbox as they enter and exit the control (without a loop). I'd suggest a single function, based on the previous answer.

    You will still need to populate the default text in both the .Tag & .Text properties

    Private Sub ToggleControl(ByRef TB As Control, ByVal Hide As Boolean)
        If Hide Then
            If TB.Text = TB.Tag Then
                TB.Text = ""
                TB.ForeColor = &H80000008
            End If
        Else
            If TB.Text = "" Then
                TB.Text = TB.Tag
                TB.ForeColor = &HC0C0C0
            End If
        End If
    End Sub
    
    Private Sub TextBox1_AfterUpdate()
        Call ToggleControl(TextBox1, False)
    End Sub
    
    Private Sub TextBox1_Enter()
        Call ToggleControl(TextBox1, True)
    End Sub