こないだの、個人用マクロブックのモジュールをエクスポートする奴のついになる奴です。
エクスポートする奴はコチラ☟
コードを動かすときのポイント
1.個人用マクロブックに、「標準モジュール」として追加する必要アリ
そりゃそうか。
2.「VBA プロジェクト オブジェクト モデルへのアクセスを信頼する」へのチェックが必要
ON/OFFするマクロを書いてみました☟
3.インポートしたくないモジュールは、対象フォルダに入れておかない
対象フォルダ内の、「bas」、「cls」、「frm」を無条件に拾ってインポートするので、インポートさせたくないモジュールは除けておく必要アリです。
さて、コードです
Option Explicit Sub import_modules() Const EXPORT_DIR As String = "D:\excel_modules" Dim tmpComponent As VBComponent Dim delModuleList As Collection Dim tmpModuleName As Variant Dim tmpPath As String ' 削除(インポート)対象のモジュール名を取得 Set delModuleList = getDeleteModuleNames(EXPORT_DIR) ' インポートの前に、インポート対象と同名のモジュールを削除 For Each tmpComponent In ThisWorkbook.VBProject.VBComponents For Each tmpModuleName In delModuleList If tmpComponent.Name = getTypeLessFileName(tmpModuleName) Then Debug.Print "削除:" & getTypeLessFileName(tmpModuleName) Application.VBE.ActiveVBProject.VBComponents.Remove tmpComponent Exit For End If Next Next ' モジュールをインポート For Each tmpModuleName In delModuleList tmpPath = EXPORT_DIR & "\" & tmpModuleName Debug.Print "インポート:" & tmpPath ThisWorkbook.VBProject.VBComponents.Import tmpPath Next Set delModuleList = Nothing End Sub ' 指定フォルダ配下のファイル一覧を取得 Function getDeleteModuleNames(dir_name) As Collection Dim file As file Dim fileType As String Dim list As Collection Dim fso As Object Set fso = CreateObject("Scripting.FileSystemObject") Set list = New Collection For Each file In fso.GetFolder(dir_name).Files fileType = fso.GetExtensionName(dir_name & "\" & file.Name) If LCase(fileType) = "bas" Or LCase(fileType) = "frm" Or LCase(fileType) = "cls" Then list.Add (file.Name) End If Next Set getDeleteModuleNames = list Set fso = Nothing Set list = Nothing End Function ' 引数の文字列から、拡張子を除いた文字列を返す ' 例)「モジュールをエクスポート.bas」 → 「モジュールをエクスポート」 Function getTypeLessFileName(target_name) As String Dim fileNameTypeLess As String fileNameTypeLess = Left(target_name, InStrRev(target_name, ".") - 1) getTypeLessFileName = fileNameTypeLess End Function
まとめ
エクスポートもインポートもできるようになったので、構成管理がはかどりますね。