仅在第一次时将MouseDown / MouseUp上的空预填充文本框

时间:2019-03-25 17:06:31

标签: vba ms-word

我是vba一词的新手(只是让您知道我的问题可能很愚蠢)。

仅当我第一次单击文本框时,我才想清除该文本框。

我已经尝试过...接下来,但是我无法正确配置它

Private Sub SWName_Field_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
SWName_Field.Text = ""
End Sub

我希望代码的工作方式与工作方式完全相同,但是当我放置一些文本,例如用户输入错误或错字时,第二次单击文本框不应清除其中的文本。

感谢您的支持

2 个答案:

答案 0 :(得分:0)

任何UserForm控件中都没有内置的活动状态标识符。因此,您需要使用元数据来指定和识别是否是第一次发生鼠标下移。

为此使用控件的Tag属性。

有关详细信息,请参见代码注释。

Private Sub TextBox1_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)

    '/ Use the Tag field to determine and store the state of Text Box.
    If Len(Me.TextBox1.Tag) < 1 Then
        '/ If Mousedown for the very first  time then TextBox's tag is empty.
        '/ Go ahead, clean the textbox.
        '/ And set a text in tag.
        Me.TextBox1.Text = ""
        Me.TextBox1.Tag = "Text Cleared"
    End If

End Sub

答案 1 :(得分:0)

您可以使用Static局部变量来“记住”处理程序是否至少执行过一次:

Private Sub SWName_Field_MouseUp(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    Static executed As Boolean
    If Not executed Then
        SWName_Field.Text = ""
        executed = True
    End If
End Sub

Static本地状态与您的UserForm实例相关-只要表单实例处于活动状态,该值将被“记住”。

这意味着,如果您正在显示表单的默认实例,则状态不一定会被重置。您将要确保每次显示表单时都获得全新的默认表单状态,而不仅仅是在第一次显示时-为此,您New填写表单:

With New UserForm1
    .Show
End With

如果您只做UserForm1.Show,那么您就无法控制表单实例的创建时间-VBA可以。

您还希望控制何时销毁表单实例-您可以通过处理表单的QueryClose事件来做到这一点:

Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
    If CloseMode = VbQueryClose.vbFormControlMenu Then
        Cancel = True ' cancel the destruction of the object
        Me.Hide ' hide the instance instead
    End If
End Sub

这样,当执行达到End With时,对象将被销毁。没有它,如果用户单击“ X”按钮,该对象将被销毁,并且您可能不希望发生这种情况(尤其是在关闭表单后需要访问表单的状态时)。