1
votes

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?

2

2 Answers

1
votes

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
1
votes

Place the default value for each textbox in the .text property and the .tag property for this code to work.

When you call ControlToggle(Boolean) it will look through all the controls (but only target TextBoxes). If you passed True, it will hide the text in the control if the value of the textbox is the default value (located in the .tag property). If you pass False, it will find any blank fields and re-populate it with the default field.

Private Sub ControlToggle(ByVal Hide As Boolean)

    Dim oControl As Control
    For Each oControl In Me.Controls
        If TypeName(oControl) = "TextBox" Then
            If Hide Then
                If oControl.Text = oControl.Tag Then
                    oControl.Text = ""
                    oControl.ForeColor = &H80000008
                End If
            Else
                If oControl.Text = "" Then
                    oControl.Text = oControl.Tag
                    oControl.ForeColor = &HC0C0C0
                End If
            End If

        End If
    Next

End Sub