AddFromFile, AddFromString Methods Example

The following function uses the AddFromString and AddFromFile methods to add a string and the contents of a text file to a standard module:

Function AddTextToModule(strModuleName As String, _
     strFileName As String, strText As String) As Boolean
    Dim mdl As Module

    On Error GoTo Error_AddTextToModule
    DoCmd.OpenModule strModuleName
    Set mdl = Modules(strModuleName)
    mdl.AddFromFile strFileName
    mdl.AddFromString strText
    AddTextToModule = True

Exit_AddTextToModule:
    Exit Function

Error_AddTextToModule:
    MsgBox Err & ": " & Err.Description
    AddTextToModule = False
    Resume Exit_AddTextToModule
End Function

You could call the preceding function from a procedure such as the following. Create a text file called Functions.txt, add some Visual Basic procedures, and save it in the directory, My Documents. Then paste both the preceding procedure and the following procedure into a new standard module in the Northwind sample database. Run the following procedure:

Sub AddFunctionsFromText()
    Dim strModuleName As String, strFileName As String
    Dim strText As String

    strModuleName = "Utility Functions"
    strFileName = "C:\My Documents\Functions.txt"
    strText = "Public intX As Integer" & vbCrLf _
        & "Const conPathName As String = " _
        & """C:\Program Files\Microsoft Office\Office\Samples\"""
    If AddTextToModule(strModuleName, strFileName, _
         strText) = True
     Then
        Debug.Print "String and file contents added successfully."
    Else
        Debug.Print "String and file contents not " _
            & "added successfully."
    End If
End Sub

The next example creates a new form and adds a string and the contents of the Functions.txt file to its module. Run the following procedure from a standard module:

Sub AddTextToFormModule()
    Dim frm As Form, mdl As Module

    Set frm = CreateForm
    Set mdl = frm.Module
    mdl.AddFromString "Public intY As Integer"
    mdl.AddFromFile "C:\My Documents\Functions.txt"
End Sub