Creating a New Module

You may want to add a new module with Visual Basic in order to add text from a file. The following example uses the AddFromFile method to add the contents of a text file to a new module. The procedure saves the new module with the same name as the text file.

'***************** Code Start *******************
'Code from Microsoft Knowledge Base

Function AddFromTextFile(strFileName) As Boolean
   Dim strModuleName As String
   Dim intLength As Integer, intPosition As Integer
   Dim mdl As Module
   ' Store file name in variable.
   strModuleName = strFileName
   ' Remove directory path from string.
   Do
     ' Find \ character in string.
     intPosition = InStr(strModuleName, "\")
     If intPosition = 0 Then
       Exit Do
     Else
       intLength = Len(strModuleName)
       ' Remove path from string.
       strModuleName = Right(strModuleName, Abs(intLength - intPosition))
     End If
   Loop
   ' Remove file extension from string.
   intPosition = InStr(strModuleName, ".")
   If intPosition > 0 Then
     intLength = Len(strModuleName)
     strModuleName = Left(strModuleName, intPosition - 1)
   End If
   ' Create new module.
   DoCmd.RunCommand acCmdNewObjectModule
   ' Save module with name of text file, excluding path and extension.
   DoCmd.Save , strModuleName
   ' Return reference to Module object.
   Set mdl = Modules(strModuleName)
   ' Add contents of text file.
   mdl.AddFromFile strFileName
   ' Save module with new text.
   DoCmd.Save
End Function

'****************** Code End ********************

Return to Example List