多个外部工作簿的Worksheet_Change事件

时间:2019-06-14 10:10:42

标签: excel vba class events

我有一个类模块,充当外部工作簿的Worksheet_Change事件。我正在重做我的项目,并且当前设置仅允许一个外部工作簿sheet_change事件。但是,我希望此事件侦听多个工作簿上的更改。

直到代码中途才知道工作簿的数量,因此我无法为每个工作簿创建预定数量的类。

模块Functions

Dim oWb2 As New UpdaterUnkowns

Public Function
'Code...
Set oWb2.Workbook = newfile
End Function

类模块UpdaterUnknowns

Public WithEvents m_wb As Workbook
Public CellVal As String

Public Property Set Workbook(wb As Workbook)
    Set m_wb = wb
End Property

Public Property Get Workbook() As Workbook
    Set Workbook = m_wb
End Property

Public Sub m_wb_SheetChange(ByVal Sh As Object, ByVal Target As Range)

'Code...

End Sub

Set oWb2.Workbook = newfile设置类模块的工作簿。我可以将多个工作簿传递给活动吗?

1 个答案:

答案 0 :(得分:2)

要处理所有打开的工作簿,可以执行以下操作:

Dim UU_collection As Collection
sub mysub()
   Set uu_collection = New Collection
   Dim wb As Workbook
   For Each wb In Application.Workbooks
      Dim oWb2 As UpdaterUnknowns
      Set oWb2 = New UpdaterUnknowns
      Set oWb2.Workbook = wb
      uu_collection.Add oWb2
   Next wb
End Sub