vba 按键时清除文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11159585/
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
Clear Textbox on key press
提问by Ish
Is there any way to clear the textbox on keypress like in excel.
有没有办法像excel一样清除按键上的文本框。
I tried the following code but it clears the text when clicking on the textbox. I want it to clear it when a certain key is pressed.
我尝试了以下代码,但在单击文本框时会清除文本。我希望它在按下某个键时清除它。
Private Sub Text10_GotFocus()
Text10.Value = ""
End Sub
采纳答案by HansUp
You could select the control's entire text content whenever that control gets focus. Then your keypress would replace the selected text.
只要该控件获得焦点,您就可以选择该控件的整个文本内容。然后您的按键将替换所选文本。
If you want that to happen for every text box on every form, you can set "Behavior entering field" setting to "Select entire field". (In Access 2007, find that setting from Office Button -> Access Options -> Advanced, then look under the Editing heading of that dialog. For Access 2003, see this page.)
如果您希望每个表单上的每个文本框都发生这种情况,您可以将“行为输入字段”设置为“选择整个字段”。(在 Access 2007 中,从 Office 按钮 -> 访问选项 -> 高级中找到该设置,然后在该对话框的编辑标题下查看。对于 Access 2003,请参阅此页面。)
Not only will that setting be applied to form controls, but also to tables and queries in datasheet view. If that's not what you want, you can use VBA in your form's module to select the text for only specific controls:
该设置不仅会应用于表单控件,还会应用于数据表视图中的表和查询。如果这不是您想要的,您可以在表单模块中使用 VBA 来为特定控件选择文本:
Private Sub MyTextBox_GotFocus()
Me.MyTextBox.SelStart = 0
Me.MyTextBox.SelLength = Len(Me.MyTextBox)
End Sub
If you want to do that for multiple controls, you could create a general procedure:
如果要对多个控件执行此操作,可以创建一个通用过程:
Private Sub SelectWholeField()
Me.ActiveControl.SelStart = 0
Me.ActiveControl.SelLength = Len(Me.ActiveControl)
End Sub
Then call that procedure from the got focus event of an individual control like this:
然后从单个控件的获得焦点事件调用该过程,如下所示:
Private Sub MyTextBox_GotFocus()
SelectWholeField
End Sub
回答by Jeff
Declare a Form Level variable
声明一个表单级别变量
Private CanDelete as Boolean
When the TextBox receives focus, set CanDelete to True
当 TextBox 获得焦点时,将 CanDelete 设置为 True
Private Sub txtTest_GotFocus()
CanDelete = True
End Sub
On the KeyPress event, clear the text if CanDelete is True
在 KeyPress 事件上,如果 CanDelete 为 True,则清除文本
Private Sub txtTest_KeyPress(KeyAscii As Integer)
If CanDelete Then
Me.txtTest = ""
CanDelete = False
End If
End Sub
回答by SeanC
Private Sub Field1_KeyPress(KeyAscii As Integer)
If KeyAscii = 65 Then Me.Field1 = ""
'Or: If Chr(KeyAscii) = "A" Then Me.Field1 = ""
End Sub
change the number to the ascii value of whatever key you are wanting to use to clear the field
将数字更改为您要用于清除字段的任何键的 ascii 值