一行调用多个Sub

时间:2019-05-27 12:52:56

标签: excel vba

我试图用一行调用多个Sub,这时我正在这样做(这不切实际)

' Textbox1
' Textbox2
' Textbox3
' Textbox...
' Textbox100

Private Sub TextBox1_AfterUpdate()

    Call TextBox1_Function

End Sub

Private Sub TextBox2_AfterUpdate()

    Call TextBox2_Function

End Sub

Private Sub TextBox3_AfterUpdate()

    Call TextBox3_Function

End Sub

' ......................... till Textbox100

我现在想知道是否可以这样:

' Textbox1
' Textbox2
' Textbox3
' Textbox...
' Textbox100

Private Sub TextBox1_AfterUpdate()

    ' 1 - Get this Sub Object (I don't know if it's possible)
    ' 2 - Then Call the function 
    Call TextBox_Function OBJ_Name

End Sub

Function TextBox_Function(OBJ as Object)

    ' Do some code

End Function

或者更好的选择...用更少的代码行...因为我有10个类别的文本,每个类别都有100个文本框...

某些文本框的功能必须有所不同,因此我不能使用“ For Each Textbox .....”

1 个答案:

答案 0 :(得分:3)

您可以通过添加处理事件的类来为多个文本框添加事件处理程序。该类可以包含一个BoxType,因此您可以为每个TextBox定义它是哪种类型,然后在事件处理程序中可以通过它们的BoxType来区分这些框。

  1. 添加一个Class Module并将其命名为clsTextBox并粘贴以下代码:

    Option Explicit
    
    Public WithEvents pTbx As MSForms.TextBox
    Public BoxType As String
    
    Private Sub pTbx_AfterUpdate()
        Select Case BoxType
            Case "TypeA"
                Debug.Print "Type A update " & pTbx.Name
            Case "TypeB"
                Debug.Print "Type B update " & pTbx.Name
        End Select
    End Sub
    
    Private Sub pTbx_Change()
        Select Case BoxType
            Case "TypeA"
                Debug.Print "Type A change " & pTbx.Name
            Case "TypeB"
                Debug.Print "Type B change " & pTbx.Name
        End Select
    End Sub
    

    创建所需的事件。

    • pTbx是指触发事件的文本框。
    • BoxType指定触发事件的文本框的类型。
  2. 初始化您的文本框。因此,请将以下代码粘贴到用户表单中

    Option Explicit
    
    Private mClsTbx() As clsTextBox
    
    Private Sub InitBoxes(ByVal BoxType As String, ByVal BoxNames As Variant)
        Dim StartIdx As Long
    
        On Error Resume Next
        StartIdx = UBound(mClsTbx) + 1
        On Error GoTo 0
        ReDim Preserve mClsTbx(StartIdx + UBound(BoxNames))
    
        Dim i As Long
        For i = 0 To UBound(BoxNames)
            Set mClsTbx(i + StartIdx) = New clsTextBox
            Set mClsTbx(i + StartIdx).pTbx = Controls(BoxNames(i))
            mClsTbx(i + StartIdx).BoxType = BoxType
        Next i
    End Sub
    
    
    Private Sub UserForm_Initialize()
        'here we define which TextBox belongs to which type
        InitBoxes BoxType:="TypeA", BoxNames:=Array("TextBoxA1", "TextBoxA2")
        InitBoxes BoxType:="TypeB", BoxNames:=Array("TextBoxB1", "TextBoxB2")
        'add more types here
    End Sub