VBA:检测用户窗体的任何文本框中的更改 [英] VBA: Detect changes in any textbox of the userform

查看:676
本文介绍了VBA:检测用户窗体的任何文本框中的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个用户表单有很多文本框,我需要检测每个文本框的更改。所以我为表单中的每个文本框写了一个子例程,并且显示了一大块代码。
由于每个文本框的代码都是相同的,我想优化它。那么可以写一个子例程来检测表单的任何文本框的变化?

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?

推荐答案

唯一的方法是实现是使用一个类与 WithEvents

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

这是一个最小的例子:

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

和Userform中的代码,假设你想处理每个Textbox的事件

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

这篇关于VBA:检测用户窗体的任何文本框中的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆