SetFocus 方法、LineCount 和 TextLength 属性示例

以下示例使用 LineCountTextLength 属性以及 SetFocus 方法对 TextBox 中的字符和文本行数进行计数。

在此示例中,用户可向 TextBox 中键入内容,还可以检索 LineCountTextLength 属性的当前值。

若要使用此示例,请将此示例代码复制到窗体的 Declarations 部分。 确定窗体包含以下控件:

  • 一个名为"TextBox1"的 TextBox
  • 一个名为"CommandButton1"的 CommandButton
  • 两个名称分别为"Label1"和"Label2"的 Label 控件。
'Type SHIFT+ENTER to start a new line in the text box. 
 
Private Sub CommandButton1_Click() 
 'Must first give TextBox1 the focus to get line 
 'count 
 TextBox1.SetFocus 
 Label1.Caption = "LineCount = " _ 
 & TextBox1.LineCount 
 Label2.Caption = "TextLength = " _ 
 & TextBox1.TextLength 
End Sub 
 
Private Sub UserForm_Initialize() 
 CommandButton1.WordWrap = True 
 CommandButton1.AutoSize = True 
 CommandButton1.Caption = "Get Counts" 
 
 Label1.Caption = "LineCount = " 
 Label2.Caption = "TextLength = " 
 
 TextBox1.MultiLine = True 
 TextBox1.WordWrap = True 
 TextBox1.Text = "Enter your text here." 
End Sub

支持和反馈

有关于 Office VBA 或本文档的疑问或反馈? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。