如果您最终拥有大量文本框,则在自定义类中自定义事件处理程序可能会更容易。
在标准模块中,放置一个全局范围的集合变量
Public gcolTextboxes As Collection
创建一个名为 CTbxEvents 的自定义类模块
Private WithEvents mtb As MSForms.TextBox
Public Property Get tb() As MSForms.TextBox
Set tb = mtb
End Property
Public Property Set tb(otb As MSForms.TextBox)
Set mtb = otb
End Property
Private Sub mtb_Change()
tb.Font.Size = 11
tb.Font.Bold = True
End Sub
最后,在 ThisDocument 中,在文档打开时加载所有文本框。
Private Sub Document_Open()
Dim f As Field
Dim clsTbxEvents As CTbxEvents
'Globally scoped collection to hold the classes
Set gcolTextboxes = New Collection
'Loop throught the fields
For Each f In Me.Fields
'Only fields that are activex controls
If f.Type = wdFieldOCX Then
'only activex controsl that are textboxes
If TypeOf f.OLEFormat.Object Is MSForms.TextBox Then
'create a new class, add the textbox, add to collection
Set clsTbxEvents = New CTbxEvents
Set clsTbxEvents.tb = f.OLEFormat.Object
gcolTextboxes.Add clsTbxEvents
End If
End If
Next f
End Sub
现在您添加的任何文本框都将使用相同的事件处理程序,并且您不必一直调用单独的子。如果你真的只有三个文本框,那可能是矫枉过正。