0

我有以下问题:

Private Sub TextBox1_Change()
   Control (this)                <<<<----- this is Empty
End Sub
Private Sub TextBox2_Change()
   Control (this)                <<<<----- this is Empty
End Sub
Private Sub TextBox3_Change()
   Control (this)                <<<<----- this is Empty
End Sub

Public Sub Control(asdf As MSForms.TextBox)
    asdf.Font.Size = 11
    asdf.Font.Bold = True    
End Sub

编译器说“this”是空的。我应该放什么来识别文本框?

谢谢

4

3 回答 3

1

当您在代码中使用括号时,您正在评估 Me.TextBox1,最终将字符串传递给 Control。如果您放下括号,它将起作用。

Private Sub TextBox1_Change()
   Control Me.TextBox1 'without the parens         
End Sub

()通常你在调用 Sub 时不使用,除非你正在使用Call

于 2013-09-09T18:43:39.677 回答
0

关键字是 C++/C#/Java 特有的this,VB/VB.NET 对应的关键字是Me

于 2013-09-09T18:04:43.927 回答
0

如果您最终拥有大量文本框,则在自定义类中自定义事件处理程序可能会更容易。

在标准模块中,放置一个全局范围的集合变量

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

现在您添加的任何文本框都将使用相同的事件处理程序,并且您不必一直调用单独的子。如果你真的只有三个文本框,那可能是矫枉过正。

于 2013-09-09T21:14:35.480 回答