您可以将代码添加到模块,而无需使用包含该代码的单独文本文件。

下面的宏显示了如何完成此操作。必须自定义宏,使其包含在要添加的代码中:

Sub InsertProcedureCode(ByVal wb As Workbook, ByVal InsertToModuleName As String)

' inserts new code in module named InsertModuleName in wb

' needs customizing depending on the code to insert

Dim VBCM As CodeModule

Dim InsertLineIndex As Long

On Error Resume Next

Set VBCM = wb.VBProject.VBComponents(InsertToModuleName).CodeModule

If Not VBCM Is Nothing Then

With VBCM

InsertLineIndex = .CountOfLines + 1

' customize the next lines depending on the code you want to insert

.InsertLines InsertLineIndex, "Sub NewSubName()" & Chr(13)

InsertLineIndex = InsertLineIndex + 1

.InsertLines InsertLineIndex, _

"    Msgbox ""Hello World!"",vbInformation,""Message Box Title""" & Chr(13)

InsertLineIndex = InsertLineIndex + 1

.InsertLines InsertLineIndex, "End Sub" & Chr(13)

' no need for more customizing

End With

Set VBCM = Nothing

End If

On Error GoTo 0

End Sub

例如:

InsertProcedureCode Workbooks("WorkBookName.xls"), "Module1"