View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Dave Peterson Dave Peterson is offline
external usenet poster
 
Posts: 35,218
Default Use VBA to create new sheet with event handlers in sheet's code

You can do it, but I wouldn't.

If you're going to share this with others, they'll have to have a security flag
set that allows you to write to the workbook's project. It's not something you
can change via code. You'll have to explain to each user how to make that
change -- and explain it again (and again and again) if they reset that flag.

Instead, I'd either use a separate template file with the code already behind
that worksheet. Then just insert that worksheet from that template file with a
command like:

Dim NewWks as Sheet
set newwks = sheets.Add(type:="c:\pathtothatfile.xlt")

or even just include a sheet (hidden) in the same workbook/addin(??) that
contains the code and copy it from there.

But if you want to try writing code that writes code, start by reading Chip
Pearson's site:
http://www.cpearson.com/excel/vbe.aspx

Here's a version of one of Chip's routines, but for a worksheet event.

Option Explicit
Sub CreateEventProcedure()

Dim VBProj As Object 'VBIDE.VBProject
Dim VBComp As Object 'VBIDE.VBComponent
Dim CodeMod As Object 'VBIDE.CodeModule
Dim LineNum As Long
Dim wks As Worksheet

Set wks = Worksheets.Add
Set VBProj = Nothing
On Error Resume Next
Set VBProj = ActiveWorkbook.VBProject
On Error GoTo 0

If VBProj Is Nothing Then
MsgBox "Can't continue--I'm not trusted!"
Exit Sub
End If

Set VBComp = VBProj.VBComponents(wks.CodeName)
Set CodeMod = VBComp.CodeModule

With CodeMod
LineNum = .CreateEventProc("Activate", "Worksheet")
LineNum = LineNum + 1
.InsertLines LineNum, " MsgBox " & Chr(34) & "Hello World" & Chr(34)
End With

End Sub

====
Heck, maybe you could even use a workbook event instead????????


VBAer wrote:

I tried for a little to do this but was unsuccessful.

Basically, I am using a standard VBA module to build a new worksheet. Using
the same VBA module, I want to write an event handler into the new
worksheet's code. i.e, when I build the new worksheet, I don't want to
separately write the event handler into the worksheet's code.

The basic question boils down to: Can a standard VBA module edit a
worksheet's code?

Is this possible?

Thanks!


--

Dave Peterson