Word VBA:以多个文本输入字段为目标,并更改_Enter()和_AfterUpdate()上的值
我正在使用Office365版本的Word。我创建了一个VBA用户表单,其中包含以帮助器文本作为初始值的文本框。我使用下面的代码清除用户输入文本字段时的值,并在字段为空时重新填充帮助器文本:Word VBA:以多个文本输入字段为目标,并更改_Enter()和_AfterUpdate()上的值,vba,ms-word,userform,Vba,Ms Word,Userform,我正在使用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 = &a
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(布尔)时,它将查看所有控件(但仅限于目标文本框)。如果传递True,则如果textbox的值是默认值(位于.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