tiredofit
Well-known Member
- Joined
- Apr 11, 2013
- Messages
- 1,834
- Office Version
- 365
- 2019
- Platform
- Windows
The following code is taken from here:
This is in CExcelEvents:
The article goes on as follows:
Where should these lines go?
I tried putting them in a worksheet module, such as:
but it didn't even compile, instead displaying this error message:
Thanks
Code:
http://www.cpearson.com/Excel/Events.aspx
This is in CExcelEvents:
Code:
Option Explicit
Public Event EventName(IDNumber As Long, ByRef Cancel As Boolean)
Sub AAA()
Dim B As Boolean
Dim IDNumber As Long
IDNumber = 1234
Cancel = False
RaiseEvent EventName(IDNumber, Cancel)
If Cancel = False Then
' Appropriate Non-Cancel Action
Else
' Appropriate Cancel Action
End If
End Sub
The article goes on as follows:
Code:
Once you have created your class with events, you need to write the code that will receive the event triggers. Note that only object modules (class modules, a user form code module, a Sheet module, or the ThisWorkbook module -- standard code modules cannot receive events) can receive event messages. In a suitable object module, declare the event class using WithEvents:
Dim WithEvents XLEvents As CExcelEvents
' More code
At some point in your code, you will need to set the XLEvents variable to an instance of the CExcelEvents class, with the code:
Set XLEvents = New CExcelEvents
Exactly when and where you put the object initialization code depends on what sort of module contains the event declaration. While it is technically possible to put the initialization of the variable in another procedure, this is generally a bad programming practice: it makes the code more difficult to debug and maintain. As a general rule, the code that initializes the events variable should be in the same class as the events variable. Of course, the actual event code must reside in the same object module as the events variable declaration. In a class module, the initialization would normally be in the Class_Initialize event. For a user form, the code would go in the UserForm_Initialize event.
Private Sub XLEvents_EventName(IDNumber Long, Cancel As Boolean)
Cancel = True ' or False -- your choice
End Sub
Where should these lines go?
Code:
Dim WithEvents XLEvents As CExcelEvents
Set XLEvents = New CExcelEvents
Private Sub XLEvents_EventName(IDNumber Long, Cancel As Boolean)
Cancel = True ' or False -- your choice
End Sub
I tried putting them in a worksheet module, such as:
Code:
Option Explicit
Dim WithEvents XLEvents As CExcelEvents
Private Sub Worksheet_Change(ByVal Target As Range)
Set XLEvents = New CExcelEvents
End Sub
but it didn't even compile, instead displaying this error message:
Code:
Compile error variable not defined
Cancel = False
Thanks