Excel VBA中的文本框提示文本 [英] Text box prompt text in Excel VBA

查看:1215
本文介绍了Excel VBA中的文本框提示文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您知道有时您会在输入字段中看到提示输入答案的文本吗?当您单击它时,它消失了,但是如果您取消选择而没有键入任何内容,则会返回它.

You know how sometimes you see text in an input field prompting for an answer? When you click it, it goes away, but comes back if you deselect without having typed anything.

如何在Excel文本框中完成此操作?可以做到吗?

How do I accomplish this in an Excel text box? Can this be done at all?

如果我将click宏附加到文本框,并且该宏能够分辨出单击了哪个文本框,我想我可以完成此操作,但是click宏的问题在于它无法让您选择对象首先,因此您不知道单击了什么.而且我不想在Click宏代码中对文本框名称进行硬编码.

I think I could accomplish this if I attach a click macro to the text box and the macro can be able to tell what text box was clicked, but the problem with the click macro is it won't let you select the object first, so you have no idea what was clicked. And I don't want to hard code the text box name in the click macro code.

推荐答案

我认为您是指用户窗体中的占位符".我使用的两个技巧是"tag"属性以及 Enter Exit 事件.首先,创建将在 Enter (焦点)和 Exit (模糊)后触发的子模块.

I think you're referring to a "placeholder" in a UserForm. The two tricks that I use to achieve this are the "tag" property and Enter and Exit events. First, create your sub modules that will fire upon Enter (focus) and Exit (blur).

Sub TB_enter(TB_name)
    If Len(Me.Controls(TB_name).Tag) = 0 Then
        Me.Controls(TB_name).Tag = Me.Controls(TB_name).Value
        Me.Controls(TB_name).Value = vbNullString
    End If
End Sub
Sub TB_exit(TB_name)
    If Len(Me.Controls(TB_name).Value) = 0 Then
        Me.Controls(TB_name).Value = Me.Controls(TB_name).Tag
        Me.Controls(TB_name).Tag = vbNullString
    End If
End Sub

接下来,对于用户窗体上文本框的每个实例,在查看对象"模式下双击该文本框.这将自动为更改事件创建一个私有订阅.转到工具栏的右上角,然后将更改"下拉列表更改为输入".这将为 Enter 事件创建一个新的Private Sub.再次重复此过程,但是选择退出"以创建退出事件.现在,只需将以下代码分别复制到 Enter Exit 事件中(我已经为第一个文本框使用了默认名称,但这在调用事件时是独立于名称的).

Next, for each instance of your textbox on your userform, double click on the textbox while in View Object mode. This will automatically create a Private Sub for the change event. Head to the upper right hand corner of the toolbar and change the "Change" drop down list to "Enter". This will create a new Private Sub for the Enter event. Repeat this process again, but select "Exit" to create the Exit event. Now, simply copy the following code into the Enter and Exit events respectively (I've used the default name for the first textbox, but this is name independent when calling the events).

Private Sub TextBox1_Enter()
    TB_enter ActiveControl.Name
End Sub
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    TB_exit ActiveControl.Name
End Sub

如果将这些调用放置在外部模块中,只需将"Me"替换为用户窗体的名称即可.

If you are placing these calls in an external module, simply replace "Me" with the name of the UserForm.

这篇关于Excel VBA中的文本框提示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆