Add content to a module from a file using VBA in Microsoft Excel

If you don't want to add a complete module, you can add just the missing procedures
to an existing module by using the macro below. It adds the content of a text file to an existing module:

Sub ImportModuleCode(ByVal wb As Workbook, _
    ByVal ModuleName As String, ByVal ImportFromFile As String)
' imports code to ModuleName in wb from a textfile named ImportFromFile
Dim VBCM As CodeModule
    If Dir(ImportFromFile) = "" Then Exit Sub
    On Error Resume Next
    Set VBCM = wb.VBProject.VBComponents(ModuleName).CodeModule
    If Not VBCM Is Nothing Then
        VBCM.AddFromFile ImportFromFile
        Set VBCM = Nothing
    End If
    On Error GoTo 0
End Sub

Example:

ImportModuleCode ActiveWorkbook, "TestModule", "C:\FolderName\NewCode.txt"

Leave a Reply

Your email address will not be published. Required fields are marked *

Terms and Conditions of use

The applications/code on this site are distributed as is and without warranties or liability. In no event shall the owner of the copyrights, or the authors of the applications/code be liable for any loss of profit, any problems or any damage resulting from the use or evaluation of the applications/code.

Visit Us On TwitterVisit Us On FacebookVisit Us On Google PlusVisit Us On Youtube