将代码添加到Workbook_Open()

时间:2015-09-11 08:25:23

标签: excel excel-vba vba

我正在尝试编写一段代码,将以下代码放入已创建的新excel工作簿中。生成的代码应该是

Private Sub Workbook_Open()
  ThisWorkbook.RefreshAll
End Sub

目前我正在使用以下代码,新工作簿是活动工作簿。

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

有谁知道我哪里出错或什么能帮助我?

0 个答案:

没有答案