@
Saee Mane
1- The code stops working when closing the workbook because that's what it is supposed to do. The cell click event is is applicable only to the workbook containing the code... If we wanted to make the cell click event globally available throughout all workbooks, we would need to place the code in an addin .
2-3 - The purpose of "Start Cell Click Event" and "Stop Cell Click Event" is obvious. One is to make the cell click event work and the other to make it stop working. The first button is assigned the "Start" SUB and the second button is assigned the "Stop" SUB.
Note that the code also starts the Cell Click Event
automatically when opening\activating the workbook and stops the Cell Click Event
automatically when closing. That's probably the source of your confusion.
VBA Code:
Private Sub Workbook_Activate()
EnableCellClickEvent = True
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
EnableCellClickEvent = False
End Sub
The reason I added the two buttons for enabling\disabling the event was just for illustration purposes or in case the user wanted to disable the click event prematurely before the workbook is closed.
In a normal scenario, the click event would be enabled automatically upon opening the workbook and would be disabled automatically on closing . This should be achieved via the above two workbook events and therefore, we wouldn't need the two buttons.
"basMod" is the module containing all the heaving lifting. Basically, it launches a second instance of excel that is invisible behind the scenes whose purpose is to remotely monitor all the mouse clicks.
Right before a mouse click is performed, the code in the remote excel instance calls the
OnCellClick event procedure located in the current excel instance and passes the cell target to it .
The OnCellClick event procedure in the current excel instance is where the user decides what to do each time a cell click is carried out. This makes the code extremely flexible and intuitive as it mimics the signature of standard events.
Now, if you ask why we run the code that monitors the mouse clicks from a second instance of excel behind the scenes, the answer is because the code uses a windows hook (WH_MOUSE_LL) which if ran from the current excel instance, it would make excel unstable at best and would crash the entire application should an unhandled error occur or a loss of state happen... Placing the mouse hook code in a second excel instance prevents all potential issues.
The "basMod" module should be left untouched . The user would only need to deal with the
OnCellClick event procedure that is located in the
ThisWorkbook module. Just like how we work with other excel standard events.