VBA:检测用户表单的任何文本框中的更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24403121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 03:35:16  来源:igfitidea点击:

VBA: Detect changes in any textbox of the userform

vbaeventsuserform

提问by Millik

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?

有一个用户窗体有许多文本框,我需要检测每个文本框的变化。所以我为表单中的每个文本框编写了一个子程序,结果是一大段代码。由于每个文本框的代码都是相同的,我想对其进行优化。那么是否可以只编写一个子程序来检测表单的任何文本框的变化?

回答by z??

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

实现这一目标的唯一方法是使用一个类 WithEvents

Here's a minimal example:

这是一个最小的例子:

Code for the class module named mytextbox:

名为 的类模块的代码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

还有Userform里面的代码,假设你要处理每个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