Thanks to everyone who replied here and sent emails. I finally got it
all figured out and just wanted to post the result to help others who
might have a similar problem. First the code, then the explanation.
THE CODE:
Public Sub DoStuff()
Dim VBProj As VBProject
Dim VBComp As VBComponent
Dim VBCodeMod As CodeModule
Dim StartLine As Long
Dim testCodeString As String
Application.ScreenUpdating = False
''add a new (temporary) workbook
Workbooks.Add
''rename the activesheet per the user's textbox input value
ActiveSheet.Name = UserForm1.TextBox1.Value
''write event for the new worksheet
Set VBProj = ActiveWorkbook.VBProject
For Each VBComp In VBProj.VBComponents
If VBComp.Type = vbext_ct_Document Then
If (VBComp.Properties("Name").Value = ActiveSheet.Name)
Then
Set VBCodeMod = VBComp.CodeModule
''--------------------------------------------------------
'' METHOD 2: Use .AddFromString
''--------------------------------------------------------
testCodeString = _
"Public Sub Worksheet_Calculate()" & vbCr & _
" Dim prompt As String" & vbCr & vbCr & _
" ''test line - comment 1" & vbCr & _
" prompt = ""RUNNING: Worksheet_Calculate""" &
vbCr & _
" MsgBox prompt" & vbCr & _
"End Sub"
VBCodeMod.AddFromString testCodeString
''--END METHOD 2
CODE-------------------------------------
End If
End If
Next
''move the new sheet with event code to the other workbook
Sheets(1).Move Befo=Workbooks("TestWorkbook.xls").Sheets(1)
''activate and close/delete the previously added (temporary)
workbook
Workbooks(Workbooks.Count).Activate
ActiveWorkbook.Close (False)
Application.ScreenUpdating = True
End Sub
THE EXPLANATION:
I got this idea from another post where the post-er mentioned being
able to write code to a worksheet in a different workbook, but not the
workbook running the userform. So, I decided to try creating a
temporary workbook, writing the Worksheet event code in a sheet in the
new workbook and then just moving the worksheet to the old workbook.
This worked...Now, the original workbook contains a new sheet (named by
the user), the new sheet contains the appropriate event code, and the
userform stays open - ready for another user input (worksheet name).
If anyone would like to chat about this further, please email me since
i'll probably stop watching this thread.
Happy programming...
Troy