I am trying to write a piece of code that will put the following code into a new excel workbook that has been created. The generated code should be
Private Sub Workbook_Open()
ThisWorkbook.RefreshAll
End Sub
At the moment I am using the following code, and the new workbook is the active workbook.
Public Sub AddNewModule()
Dim proj As VBIDE.VBProject
Dim comp As VBIDE.VBComponent
Set proj = ActiveWorkbook.VBProject
Set comp = proj.VBComponents.Add(vbext_ct_StdModule)
comp.Name = "MyNewModule"
Set codeMod = comp.CodeModule
With codeMod
lineNum = .CountOfLines + 1
.InsertLines lineNum, "Private Sub Workbook_Open()
lineNum = lineNum + 1
.InsertLines lineNum, "ThisWorkbook.RefreshAll"
lineNum = lineNum + 1
.InsertLines lineNum, "End Sub"
End With
End Sub
Does anyone know where I am going wrong or anything that can help me?
Is this what you are trying (Short And Sweet)?
Option Explicit
Sub Sample()
With ActiveWorkbook.VBProject.VBComponents(ActiveWorkbook.CodeName).CodeModule
.InsertLines Line:=.CreateEventProc("Open", "Workbook") + 1, _
String:=vbCrLf & "ThisWorkbook.RefreshAll"
End With
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.