vba 单击文本框时清除文本框中的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4068576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 10:54:24  来源:igfitidea点击:

Clear text in textbox upon clicking it

vbatextbox

提问by maple

I have text in a textbox, which says "NEW NAME HERE"

我在一个文本框中有文字,上面写着“这里有新名字”

Is it possible with in VBA to clear this text as soon as the user clicks in that textbox?

一旦用户单击该文本框,是否可以在 VBA 中清除此文本?

If so could anyone please let me know how?

如果是这样,有人可以让我知道如何吗?

THANKS-

谢谢-

回答by Adam Ralph

Assuming the TextBox is named TextBox1, the following should work

假设 TextBox 被命名TextBox1,以下应该工作

Private Sub TextBox1_GotFocus()
    TextBox1.Text = ""
End Sub

回答by Gertsen

I know it's an old post, but I just stumbled upon it, and thought I'd add an answer. Maybe someone will find it useful some day :-)

我知道这是一个旧帖子,但我只是偶然发现了它,并认为我会添加一个答案。也许有一天有人会发现它有用:-)

I would check the current value before clearing the content. That way it clears the content when you first click it, but if you click it again later (to edit the name perhaps) it does nothing, allowing edits without having to start over.

我会在清除内容之前检查当前值。这样它会在您第一次单击时清除内容,但是如果您稍后再次单击它(可能是为了编辑名称),它什么也不做,允许编辑而不必重新开始。

Assuming the TextBox is named TextBox1and the placeholder text is NEW NAME HERE, the following should work

假设 TextBox 已命名TextBox1且占位符文本为NEW NAME HERE,则以下应该有效

Private Sub TextBox1_Enter()
    If TextBox1.Text = "NEW NAME HERE" Then
        TextBox1.Text = ""
    End If
End Sub

To restore the placeholder text if the textbox is left empty:

如果文本框留空,要恢复占位符文本:

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    If Trim(TextBox1.Text) = "" Then
        TextBox1.Text = "NEW NAME HERE"
    End If
End Sub

Tested in Word 2010 VBA

在 Word 2010 VBA 中测试

回答by J. Russell

I tried it without the Handles part (like the other person who had answered) and that did nothing. I've confirmed the code below works for me.

我在没有 Handles 部分的情况下尝试了它(就像另一个回答的人一样),但什么也没做。我已经确认下面的代码对我有用。

Private Sub txtNewNameHere_GotFocus() Handles txtNewNameHere.GotFocus
    txtNewNameHere.Text = ""
End Sub

Hopefully this helps someone, even though this question is a bit old.

希望这对某人有所帮助,尽管这个问题有点老了。

回答by Dagon

Private Sub Textbox1_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Textbox1.MouseClick
    textbox1.clear()
End Sub

try this. i just this code in daniweb.

尝试这个。我只是在 daniweb 中的这段代码。