我有一个按钮,可以创建一个新工作簿并另存为新工作簿。是否可以在新创建的工作簿的工作表中自动添加代码?怎么做?
例如,我有事件代码。我想将其应用于将要创建的每个工作簿,而无需打开新工作簿并手动添加代码。我还希望保护项目。
在 vba 宏中这可能吗?
答案1
Sub CreateWorkbookWithWorksheetProcedures()
Dim wbk As Workbook
Dim objVBProj As Object
Dim objVBComp As Object
Dim objCodeMod As Object
Dim lLineNum As Long
Dim sProcLines As String
' Create new workbook
Set wbk = Workbooks.Add
Set objVBProj = wbk.VBProject
Set objVBComp = objVBProj.VBComponents("Sheet1")
Set objCodeMod = objVBComp.CodeModule
' Add event procedure
With objCodeMod
lLineNum = .CreateEventProc("Change", "Worksheet")
lLineNum = lLineNum + 1
.InsertLines lLineNum, " MsgBox ""Hello World"""
End With
' Add common procedure
lLineNum = objCodeMod.CountOfLines + 1
sProcLines = "Sub HelloWorld()" & vbCrLf & _
" MsgBox ""Hello, World""" & vbCrLf & _
"End Sub"
objCodeMod.InsertLines lLineNum, sProcLines
' Save workbook
wbk.SaveAs "c:\tmp\wbk.xlsm", xlOpenXMLWorkbookMacroEnabled
wbk.Close
End Sub