excel - VBA占位符文本仅在键入时消失,而不是在 UserFrom 上输入文本框时消失
问题描述
' 我正在寻找创建占位符文本(重影文本)以帮助用户知道在该字段中输入什么,但我希望它的行为与在线表单非常相似,其中占位符文本在输入文本框时不会消失,但是仅当您在其中输入新文本时才会消失。
' enterfieldbehavior is set to 1 - fmEnterFieldBehaviorRecallSelection in properties to avoid selecting placeholder text
Private Sub userform_initialize()
TextBox2.Value = "Name" 'upon starting UserForm, the placeholder text is launched in the textbox
TextBox2.ForeColor = &H8000000C 'grey
End Sub
Private Sub TextBox2_Enter()
If TextBox2.Text <> "Name" Then
TextBox2.SelStart = TextBox2.SelLength 'Upon entering the textbox, the cursor is placed only at the start and not the middle or end of the placeholder text
Else
' I need the oppositie of the above, to put the cursor at the end of text as the placeholder text is gone
End If
End Sub
Private Sub TextBox2_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
TextBox2.SelStart = TextBox2.SelLength ' If a user uses the mouse to enter the textbox
End Sub
Private Sub TextBox2_Change()
If TextBox2.Text <> "Name" Then
TextBox2.Text = ""
TextBox2.ForeColor = &H8000000C 'grey
Else
TextBox2.Value = TextBox2.Value ' This is where I'm lost as I want to earse the holder text, and let the user type whatever they want
TextBox2.ForeColor = vbBlack
End If
End Sub
Private Sub TextBox2_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If TextBox2.Text = "" Then
TextBox2.Text = "Name" ' If there are no changes to the textbox, replace the placeholder text
TextBox2.ForeColor = &H8000000C 'grey
Else
End If
End Sub
解决方案
这是我的做法:
Private Sub Label1_Click()
TextBox1.SetFocus
End Sub
Private Sub TextBox1_Change()
Label1.Visible = Len(TextBox1.Text) = 0
End Sub
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Label1.Visible = Len(TextBox1.Text) = 0
End Sub
Private Sub UserForm_Initialize()
With Label1
.SpecialEffect = fmSpecialEffectSunken
.BackColor = vbGrayText
.Caption = " Name"
End With
End Sub
推荐阅读
- python - 如何使用python比较两个数据框并获取不匹配的行?
- api - 如何在 SOAPUI 中的 JSONPath 匹配配置中断言多个值 - REST
- powershell - 使用 Powershell 向现有 CSV 添加值
- javascript - DanfoJS 使用 Dataframes 进行类似应用的操作
- python - 从我的列表中的整数中减去 1 直到零
- python - PANDAS - 如何更改条的大小和颜色?
- excel - 使用日期值写入 COUNTIFS
- opengl - glMultiDrawArraysIndirect instanceID 和 basInstance 在一次通过所有绘图调用时表现不同?
- python - 在 Pycharm 的 Mac M1 上找不到 Brew 安装的软件包
- google-sheets - 谷歌表格从命名范围中查找指定的日期和时间显示描述从该命名范围