从模块为另一个WB添加一个事件

时间:2015-07-28 20:34:09

标签: excel vba excel-vba events

这个问题可能已经回答了,但我似乎找不到我要找的答案。我正在创建一个模块,在调用它时会创建一个新工作簿并将信息从此工作簿传输到新工作簿。我想使用这个宏为这本新工作书添加一个事件,但没有运气。目前我有以下内容:

Public Sub TemplateCreate()
Dim NewBook as Workbook
set NewBook = addnew
End Sub

Function Addnew() as Object
Application.SheetsInNewWorkbook = 2
Application.EnableEvents = True
Set AddNew = Workbooks.Add
    With AddNew
        .SaveAs Filename:="test.xls"
    End With
End function

上面的代码效果很好,但是当添加dim withEvents Newbook作为工作簿时,我收到一个错误:仅对Object模块有效。是否有类似的代码行使其适用于模块?

我尝试添加以下事件功能,但没有运气使其成功:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'Tried changing between target and thisWB
If thisWB.Sheets("sheet1").Cells.Count = 1 And IsEmpty(thisWB.Sheets("sheet1")) Then thisWB.Sheets("sheet1").Interior.Color = vbBlue
End Sub

感谢您的帮助!

1 个答案:

答案 0 :(得分:4)

Here's a simple example:

In Class module named "clsWB":

Option Explicit

Private WithEvents m_wb As Workbook

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

'EDIT: added Getter for workbook
Public Property Get Workbook() As Workbook
    Set Workbook = m_wb
End Property

Private Sub m_wb_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
    MsgBox "You selected " & Target.Address() & " on '" & Sh.Name & "'"
    '... or however you want to respond to the trapped event
End Sub

'EDIT2: trap sheet changes
Private Sub m_wb_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    MsgBox "You changed " & Target.Address() & _
           " to " & Target.Value & _
           " on '" & Sh.Name & "'"
    '... or however you want to respond to the trapped event
End Sub

In a regular module:

Option Explicit

Dim oWb As New clsWB

Sub Tester()
    Dim AddNew As Workbook, ns As Long

    ns = Application.SheetsInNewWorkbook 'save default
    Application.SheetsInNewWorkbook = 2
    Set AddNew = Workbooks.Add()
    Application.SheetsInNewWorkbook = ns 'restore previous default

    AddNew.SaveAs Filename:="test.xls"

    Application.EnableEvents = True 'make sure events are enabled
    Set oWb.Workbook = AddNew

    'EDIT: set value in workbook
    oWb.Workbook.Sheets("sheet2").Cells(x,y).Value = "Test"

End Sub