VBA: Detect changes in any textbox of the userform

落花浮王杯 提交于 2019-12-25 02:32:08

问题


There is a userform that has many textboxes and I need to detect changes in each. So I have write a subroutine for every textbox in the form and it turns out a large piece of code. As the code for every textbox is the same I want to optimize it. So is it possible to write just one subroutine that detect changes in any textbox of the form?


回答1:


The only way do achieve that is to use a class along with WithEvents

Here's a minimal example:

Code for the class module named mytextbox:

Private WithEvents txtbox As MSForms.TextBox


Public Property Set TextBox(ByVal t As MSForms.TextBox)
    Set txtbox = t
End Property


Private Sub txtbox_Change()
    ' code for handling the event
End Sub

And the code inside the Userform, assuming you want to handle the events of every Textbox

Private myEventHandlers As Collection

Private Sub UserForm_Initialize()
    Dim txtbox As mytextbox

    Set myEventHandlers = New Collection

    Dim c As Control
    For Each c In Me.Controls
        If TypeName(c) = "TextBox" Then
            Set txtbox = New mytextbox

            Set txtbox.TextBox = c

            myEventHandlers.Add txtbox
        End If
    Next c
End Sub


来源:https://stackoverflow.com/questions/24403121/vba-detect-changes-in-any-textbox-of-the-userform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!