I have a spreadsheet which is run each day, putting its results into a
monthly results file, Thus the results for October will be in a file
Results200610October.xls

The results are then actioned by a user, with details being updated in
the results spreadsheet.

I need to run a macro in the spreadsheet when a user who has it open,
closes it, provided it is not ReadOnly.

I had this in the ThisWorkbook code pane of a spreadsheet called Book4.xls
I also had Book5.xls open. This worked fine and I was able to step
through using the Debugger easily, and it worked.
I have Microsoft Visual Basic for Applications Extensibility reference
Library selected.

VB Code:
  1. Sub Test()
  2. Const Book = "Book5.xls"
  3.  
  4. Workbooks(Book).VBProject.VBE.CodePanes.Item(1).CodeModule.InsertLines
  5. 1, "option explicit"
  6.  
  7. Workbooks(Book).VBProject.VBE.CodePanes.Item(1).CodeModule.InsertLines
  8. 2, "SUB Test"
  9.  
  10. Workbooks(Book).VBProject.VBE.CodePanes.Item(1).CodeModule.InsertLines
  11. 3, "   MsgBox ""Hello World"""
  12.  
  13. Workbooks(Book).VBProject.VBE.CodePanes.Item(1).CodeModule.InsertLines
  14. 4, "end sub"
  15. End Sub

Then I converted it into a separate module in my App, Please note that
TargetWbk is the filename of the Spreadsheet I am creating. It is declared
as a Global and when I debug has the correct filename in.

VB Code:
  1. Option Explicit
  2. Sub FillThisWorkbookCode()
  3.     AddLines 1, "Option Explicit"
  4.     AddLines 2, "' These routines run through updating the Status."
  5.     AddLines 3, "Private Sub Workbook_BeforeClose(Cancel As Boolean)"
  6.     AddLines 4, "    ' Before Closing we will Update the Index with the
  7. relevant Status, then we will"
  8.     AddLines 5, "    ' Promote these out to the other sheets."
  9.     AddLines 6, "    If Not ThisWorkbook.ReadOnly Then"
  10.     AddLines 7, "        ThisWorkbook.Save"
  11.     AddLines 8, "    End If"
  12.     AddLines 9, "End Sub ' Workbook_BeforeClose"
  13. End Sub ' FillThisWorkbookCode
  14.  
  15. Sub AddLines(LineNumber As Long, LineText As String)
  16. Dim mmmm As Object
  17.     ' Microsoft Visual Basic for Applications Extensibility
  18.  
  19. Workbooks(TargetWbk).VBProject.VBE.CodePanes.Item(1).CodeModule.InsertLi
  20. nes LineNumber, LineText
  21. End Sub

The problem is that the above code is not adding the Macro to the
ThisWorkbook code of TargetWbk, but to the Actual Module it self in front of
the code itself.

In addition it is not letting me Break to examine the program flow in
the debugger.

Can anyone advise me as to what is causing these problems.