当有人在文本框中输入时,我如何放大文本框以容纳所有内容?目前,它只允许你看到适合文本框的内容,但我需要让它反映出输入的文本,以便用户能够检查和验证输入的内容。我需要一个解决方案,只在点击文本框时临时放大它,然后当点击另一个问题时,它会恢复到原来的正常大小。
我在想下面的代码,但它没有满足所有必要的条件:
Private Sub TextBox1_Click()
TextBox1.Height = TextBox1.LineCount * 10
End Sub
我想出了一个如何做到这一点的主意。它需要根据您的特定用户形式进行定制,但我的想法的总体结构应该是合适的。
我在UserForm_Initialize
事件期间保存了Userform和TextBox的默认值。然后,在任何TextBox_Enter
或TextBox_Change
事件期间,UserForm都会进行检查,查看是否需要调整框的大小以适应新内容。然后在TextBox_Exit
事件期间,UserForm和TextBox返回到默认大小。
这是我的UserForm:的代码模块
Private USERFORM_DEFAULT_HEIGHT As Integer
Private USERFORM_DEFAULT_WIDTH As Integer
Private TEXTBOX1_DEFAULT_HEIGHT As Integer
Private TEXTBOX1_DEFAULT_WIDTH As Integer
Private Sub UserForm_Initialize()
USERFORM_DEFAULT_HEIGHT = Me.Height
USERFORM_DEFAULT_WIDTH = Me.Width
TEXTBOX1_DEFAULT_HEIGHT = Me.TextBox1.Height
TEXTBOX1_DEFAULT_WIDTH = Me.TextBox1.Width
End Sub
Private Sub TextBox1_Change()
If Me.ActiveControl Is Me.TextBox1 Then Resize_To_Contents Me.TextBox1
End Sub
Private Sub TextBox1_Enter()
Application.OnTime Now + TimeValue("00:00:01"), "ThisWorkbook.UserForm1.Resize_To_Contents(UserForm1.TextBox1)"
End Sub
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Me.TextBox1.Height = TEXTBOX1_DEFAULT_HEIGHT
Me.TextBox1.Width = TEXTBOX1_DEFAULT_WIDTH
Me.Height = USERFORM_DEFAULT_HEIGHT
Me.Width = USERFORM_DEFAULT_WIDTH
End Sub
Public Sub Resize_To_Contents(TB As Object)
Dim NewHeight As Integer
Dim NewWidth As Integer
If Not TB.WordWrap Then
NewWidth = Len(TB.Text) * 5 + 4 'this fit my screen and default font size, you may need to adjust it.
Else
NewWidth = TB.Width
End If
NewHeight = TB.LineCount * 10.6 'this fit my screen and default font size, you may need to adjust it.
If NewHeight > TB.Height Then
Me.Height = Me.Height + NewHeight - TB.Height
TB.Height = NewHeight
End If
If NewWidth > TB.Width Then
Me.Width = Me.Width + NewWidth - TB.Width
TB.Width = NewWidth
End If
End Sub
之所以要执行Application.OnTime
,是因为LineCount
要求TextBox具有Focus,直到事件结束后才会发生这种情况。因此,我告诉脚本等待1秒,然后运行,这样TextBox就有了焦点,我就可以使用LineCount
了。