Word VBA:定位多个文本输入字段并更改 _Enter() 和 _AfterUpdate() 上的值

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

我正在使用 Office365 版本的 Word。我创建了一个 VBA 用户表单,其中包含以辅助文本作为初始值的文本框。我正在使用如下代码清除用户在文本字段中输入的值,如果他们将该字段留空则重新填充帮助文本:

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

我的表单有十几个这样的字段。我知道我可以以某种方式访问​​表单中的文本框集合,但是我可以对它们调用操作吗?如果可能的话,有人能给我举个例子吗?

将每个文本框的默认值放在 .text 属性 和 .tag 属性 中,以使此代码生效。

当您调用 ControlToggle(Boolean) 时,它将查看所​​有控件(但仅针对 TextBox)。如果传递 True,如果文本框的值为默认值(位于 .tag 属性 中),它将隐藏控件中的文本。如果您传递 False,它将查找任何空白字段并使用默认字段重新填充它。

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

我的另一个答案集中在遍历所有控件上。要切换默认文本,通过文本框进入和退出控件(无需循环)。根据之前的回答,我建议使用一个函数。

您仍然需要在 .Tag 和 .Text 属性中填充默认文本

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