功能描述
为了方便备份代码,运行一个函数,导出类、模块、窗体。当在其他vba工程使用时,可以运行另外一个函数,快速导入代码。
1、开发人员宏设置:信任对VBA工程对象模型的访问
2、引用 Microsoft Visual Basic for Applications Extensibility
3、代码
Option Explicit
' 导出模块、类模块和用户窗体
Sub ExportModulesClassesAndForms()
Dim vbComp As VBComponent
Dim FilePath As String
Dim BackupFolder As String
' 设置备份文件夹名称
BackupFolder = ThisWorkbook.Path & "\backcode\"
' 检查备份文件夹是否存在,如果不存在则创建
If Len(Dir(BackupFolder, vbDirectory)) = 0 Then
MkDir BackupFolder
End If
' 设置文件保存路径
FilePath = BackupFolder
' 遍历所有 VB 组件
For Each vbComp In ThisWorkbook.VBProject.VBComponents
Select Case vbComp.Type
Case vbext_ct_StdModule
vbComp.Export FilePath & vbComp.Name & ".bas"
Case vbext_ct_ClassModule
vbComp.Export FilePath & vbComp.Name & ".cls"
Case vbext_ct_MSForm
vbComp.Export FilePath & vbComp.Name & ".frm"
End Select
Next vbComp
End Sub
' 导入 VBA 组件(模块、类模块和用户窗体)
Sub ImportVBAComponents()
Dim fileDialog As FileDialog
Dim selectedItem As Variant
Dim vbComp As VBComponent
Dim importPath As String
' 创建文件对话框
Set fileDialog = Application.FileDialog(msoFileDialogFilePicker)
' 只允许选择 bas、cls 和 frm 文件
fileDialog.Filters.Clear
fileDialog.Filters.Add "VBA Modules", "*.bas"
fileDialog.Filters.Add "VBA Class Modules", "*.cls"
fileDialog.Filters.Add "VBA UserForms", "*.frm"
fileDialog.AllowMultiSelect = True
' 显示文件对话框
If fileDialog.Show = -1 Then
' 获取选择的文件路径
For Each selectedItem In fileDialog.SelectedItems
importPath = selectedItem
' 根据文件后缀判断是模块、类模块还是用户窗体
Select Case Right(importPath, 4)
Case ".bas"
Set vbComp = ThisWorkbook.VBProject.VBComponents.Import(importPath)
Case ".cls"
Set vbComp = ThisWorkbook.VBProject.VBComponents.Import(importPath)
Case ".frm"
Set vbComp = ThisWorkbook.VBProject.VBComponents.Import(importPath)
End Select
Next selectedItem
MsgBox "VBA 组件导入完成!", vbInformation
Else
MsgBox "没有选择文件!", vbExclamation
End If
' 释放文件对话框对象
Set fileDialog = Nothing
End Sub