为了使其更灵活(这意味着您可以将它用于很多文本框),我创建了三个处理文本框事件的类,并定义了一个自己的事件来启用相应的。禁用文本框。
Reading 在 MS 的这个主题
班级cTextboxes
Option Explicit
Private mcolTextboxes As Collection
Private Sub Class_Initialize()
Set mcolTextboxes = New Collection
End Sub
Public Sub Add(ByRef nTextbox As MSForms.Textbox, index As Long)
Dim mTextbox As cTextbox
Set mTextbox = New cTextbox
mTextbox.index = index
Set mTextbox.Parent = Me
Set mTextbox.Textbox = nTextbox
mcolTextboxes.Add mTextbox
End Sub
Public Function InitBoxes()
Dim i As Long
For i = 2 To mcolTextboxes.Count
mcolTextboxes.Item(i).Enabled = False
mcolTextboxes.Item(i).Backcolor = &H80000016
Next i
End Function
Public Function enableBox(index As Long)
If index <= mcolTextboxes.Count Then
mcolTextboxes.Item(index).Enabled = True
mcolTextboxes.Item(index).Backcolor = &H80000005
End If
End Function
Public Function disableBox(index As Long)
If index <= mcolTextboxes.Count Then
mcolTextboxes.Item(index).Enabled = False
mcolTextboxes.Item(index).Backcolor = &H80000016
End If
End Function
班级cTextbox
Option Explicit
Private WithEvents mTextbox As MSForms.Textbox
Private WithEvents mTextChange As cTextboxChange
Dim mParent As Object
Dim mIndex As Long
Public Property Set Textbox(tb As MSForms.Textbox)
Set mTextbox = tb
Set mTextChange = New cTextboxChange
End Property
Property Let index(nIndex As Long)
mIndex = nIndex
End Property
Property Get index() As Long
index = mIndex
End Property
Public Property Set Parent(nParent As Object)
Set mParent = nParent
End Property
Public Property Get Parent()
Set Parent = mParent
End Property
Property Let Enabled(nEnabled As Boolean)
mTextbox.Enabled = nEnabled
End Property
Property Let Backcolor(color As Long)
mTextbox.Backcolor = color
End Property
Private Sub mTextBox_Change()
mTextChange.ChangeIt
End Sub
Private Sub mTextChange_EnableBox()
If mTextbox.TextLength > 0 Then
mParent.enableBox index + 1
Else
mParent.disableBox index + 1
End If
End Sub
班级cTextboxChange
Option Explicit
Public Event enableBox()
Public Sub ChangeIt()
RaiseEvent enableBox
End Sub
用户表单本身包含作为示例的四个文本框并包含以下代码
Option Explicit
Dim colTextboxes As cTextboxes
Private Sub UserForm_Initialize()
Set colTextboxes = New cTextboxes
colTextboxes.Add Me.TextBox1, 1
colTextboxes.Add Me.TextBox2, 2
colTextboxes.Add Me.TextBox3, 3
colTextboxes.Add Me.TextBox4, 4
colTextboxes.InitBoxes
End Sub