Add EventListener on new sheet vba

时间:2017-05-16 09:40:07

标签: excel vba events

I have to create an Excel sheet automatically with vba.

Some cells need an Onchange Event Listener and I wanted to know if there is a way to create this Event Listener automatically by calling a macro instead of writing it down everytime in every sheet code ?

Thank you

1 个答案:

答案 0 :(得分:0)

我将回答这个问题,因为我认为它可能与其他一些人有一些相关性,所以下面的代码应该让你开始朝着正确的方向前进。

但是,本网站有一种期望,你试图帮助自己至少与我们试图帮助你的程度相同。评论者提到了VBA Object ModelApplication EventsAddIns。然后研究这些关键词(比如google搜索)不应该超出大多数人的智慧。仅仅说你不知道在哪里放置代码或做什么事情并不是真的可以接受,而且,老实说,并没有特别激励人们去帮助你 - 放另一个方式,你很幸运能得到该帖子和评论的答案。

我不想就如何编写您的具体案例进行大规模的评论交流。这里的代码是一个例子,我希望你能进一步研究它。所以这里......

插入一个课程模块(研究如果你不知道如何)并命名它 - 我称之为 cApp 。这将使您能够访问Application对象并捕获其事件,如下所示:

Option Explicit

Private WithEvents mApp As Application
Private mSheetList As Collection

Private Sub Class_Initialize()
    Dim ws As Worksheet

    'Create instance of the sheet collection
    Set mSheetList = New Collection

    'If you wanted to add any existing sheets to be checked for changes,
    'then you'd do it here.
    'Just for an example, I'm using any existing sheets whose name contains "LoP".
    For Each ws In ThisWorkbook.Worksheets
        If InStr(ws.Name, "LoP") > 0 Then
            mSheetList.Add ws
        End If
    Next

    'Create instance of Application
    Set mApp = Application
End Sub

Private Sub mApp_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Dim ws As Worksheet

    'Test if the changed sheet is in our list.

    'Check if the Sh object is a worksheet.
    If TypeOf Sh Is Worksheet Then

        'Loop through out list of sheets and see if the Sh object is in the list.
        For Each ws In mSheetList
            If Sh Is ws Then

                'Check if the changed range is in the desired range of your sheet.
                'In this example, we'll say it has to been in the range "A1:B2".
                If Not Intersect(Target, ws.Range("A1:B2")) Is Nothing Then
                    MsgBox ws.Name & "!" & Target.Address(False, False) & " has changed."
                End If

                Exit For

            End If
        Next

    End If


End Sub

Private Sub mApp_WorkbookNewSheet(ByVal Wb As Workbook, ByVal Sh As Object)

    'A new sheet has been created so add it to our sheet list.
    If Wb Is ThisWorkbook Then
        If TypeOf Sh Is Worksheet Then
            mSheetList.Add Sh
        End If
    End If
End Sub

然后,您想要创建此类的实例。我已经在标准Module中完成了它:

Option Explicit

Private oApp As cApp

Public Sub RunMe()

    'Create instance of your app class
    Set oApp = New cApp

End Sub

然后,您可以在代码中的某个位置调用RunMe例程。您可以选择在Workbook_Open()事件中执行此操作,但可以在您选择的任何地方执行此操作。

我已经对代码进行了大量评论,因此您可以看到它正在做什么,如果您不确定他们正在做什么,您可以随时研究每个关键字。< / p>