I am trying to further build on this excellent example, which already implements the best practices discussed in these very insightful RubberduckVBA.com articles:
- Abstracting away from the Excel workbook/worksheet through proxy classes;
- Utilizing the UserForm control without messing with the state of its default instance;
- Adding "Apply" logic to #2.
I would like to add to the existing example an event handler which (for simplicity's sake) reports the value of the upper-left cell of Sheet2's "changed" range in Sheet1's "A1" cell, along with the time of the change in "A2". I would normally set about doing this in Sheet2's code-behind like this:
Private Sub Worksheet_Change(ByVal Target As Range)
Sheet1.Cells(1, 1).Value2 = Target.Cells(1, 1).Value2
Sheet1.Cells(1, 2).Value2 = CStr(Now)
End Sub
but I want to know how to best achieve this in the given example, considering it is designed around the MVP pattern and utilizes workbook&worksheet abstraction through proxy interfaces - meaning zero/minimal sheet code-behind is expected.
I was able to make sense of how event-handling is implemented in the awesome Battleship tutorial but its design differs in some significant ways:
- "Battleship" follows the MVC design pattern while I would like to stick with MVP as in the example;
- "Battleship" abstracts away from its worksheets through a "View" class while I would like to have a separate proxy interface+class for each sheet;
- "Battleship" deploys the Adapter Pattern while I am fine with having my view and sheet proxy implementations coupled with the presenter (if possible with regards to event handling).
With that in mind I would absolutely love to see a code sample which adds the "Worksheet_Change" event I described above to the base project which has already implemented Workbook and Worksheet proxies and follows the MVP pattern.
Even without a code sample it would be of great help if I get those questions cleared up:
- Does the Worksheet proxy approach dictate that there should be absolutely zero sheet code-behind? Would it be a step in the wrong direction if I begin my "Worksheet_Change" event implementation inside Sheet2 (not its proxy) like this:
Public Event SheetChanged(ByVal changedRange As Range)
Private Sub Worksheet_Change(ByVal Target As Range)
RaiseEvent SheetChanged(Target)
End Sub
- If it is not absolutely necessary to use the Adapter Pattern for event handling, is it still a good idea to have the "IViewCommands" and "IViewEvents" interfaces for listing all commands sent from the Presenter to the View and events raised from the View and sent to the Presenter respectively?
- I assume I would need to use Lazy Object/Weak Reference to be able to expose events. If so, and assuming I can get the job done without an Adapter (see #2 above), does that mean that my "Sheet2Proxy" class will have to hold a weak reference to the Presenter, through its "IViewEvents" (again see #2 above) interface?