你需要的是VBE。
首先,为应用程序可扩展性添加对 Microsoft Visual Basic 的引用。
然后,我在宏安全设置中添加以启用对 VBA 项目对象模型的信任访问。
现在,以下代码将起作用:
Sub Save_cls()
Dim c As VBComponent
f = FreeFile
For Each c In ThisWorkbook.VBProject.VBComponents
If c.Type = vbext_ct_ClassModule Then
Open c.Name & ".cls" For Output As f
Print #f, c.CodeModule.Lines(1, c.CodeModule.CountOfLines)
Close f
End If
Next
End Sub
编辑:通用函数- 将它放在 VBA 模块中,因此它可用于整个工作簿并且不附加到单个工作表:
Public Sub SaveSheetCode(ByVal Sheet As Worksheet, ByVal Filename As String)
Dim c As VBComponent, f As Integer
Set c = Sheet.Parent.VBProject.VBComponents(Sheet.CodeName)
f = FreeFile
Open Filename For Output As f
Print #f, c.CodeModule.Lines(1, c.CodeModule.CountOfLines)
Close f
End Sub
用法:
... Anywhere in your book code
SaveSheetCode WorkSheets("Sheet1"), "C:\VBA\Sheet1.cls"