Transfering Code from 1 book to another?

P

Paul Watkins

I Have this piece of code that will transfer a Macro from One Book to
another Book (Book1.xls).
Book1.xls will then be closed.

ThisWorkbook.VBProject.VBComponents("Module1").Export "macro1.bas"
Workbooks("Book1.xls").VBProject.VBComponents.Import "macro1.bas"
Kill "macro1.bas"

At this point, Book1.xls has 1 module in it and no code under 'ThisWorkbook'


When I re-open 'Book1.xls' I need that macro to run automatically.
Normally this could be done by writing this line in 'ThisWorkbook'

Private Sub Workbook_Open()
Call macro1
End Sub

How do i get the above code into the microsoft excel object ' ThisWorkbook'
so that my macro will run automatically

Paul
(Getting more confused by the minute :) )
 
R

Ron de Bruin

Try something like this

Sub test()
Dim VBCodeMod As CodeModule
Dim LineNum As Long
Set VBCodeMod =
ThisWorkbook.VBProject.VBComponents("ThisWorkbook").CodeModule
With VBCodeMod
LineNum = .CountOfLines + 1
.InsertLines LineNum, _
"Private Sub Workbook_Open()" & Chr(13) & _
"Call macro1" & Chr(13) & _
"End Sub"
End With
End Sub

See Chip Pearson's site for more info
http://www.cpearson.com/excel/vbe.htm
 
P

Paul Watkins

Thanks Ron, I'll give it a go


Ron de Bruin said:
Try something like this

Sub test()
Dim VBCodeMod As CodeModule
Dim LineNum As Long
Set VBCodeMod =
ThisWorkbook.VBProject.VBComponents("ThisWorkbook").CodeModule
With VBCodeMod
LineNum = .CountOfLines + 1
.InsertLines LineNum, _
"Private Sub Workbook_Open()" & Chr(13) & _
"Call macro1" & Chr(13) & _
"End Sub"
End With
End Sub

See Chip Pearson's site for more info
http://www.cpearson.com/excel/vbe.htm
 
P

Paul Watkins

I've tried the code and it works, however the visual basic window remains
open in another workbook.
How do i write the code to close the visual basic editor?


Thanks
Paul
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top