简体   繁体   English

将代码添加到Workbook_Open()

[英]Add code to Workbook_Open()

I am trying to write a piece of code that will put the following code into a new excel workbook that has been created. 我正在尝试编写一段代码,将以下代码放入已创建的新Excel工作簿中。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM