Importing a module into access programmatically fr

2019-07-23 17:47发布

问题:

If you open Microsoft Access, then open the visual basic window so you can see the list of modules and code in your Access project. You can drag a text-based file (txt, cls, bas, etc) from windows explorer and drop it into your module folder.

This drag and drop action will import the code in the text-based file into your project and prompt you to save it (with the default name being the name of the file you dropped.

Is there a way to do this programmatically using VBA? It seems like a simple task that should have a simple solution, but I've been researching for days and can't seem to find a simple way to do it.

回答1:

Yes, that's the command LoadFromText to use.

Usage:

LoadFromText acModule, "NameOfObject", "FileName"


回答2:

You can use the VBComponents.Import method from the VBE object model. See the Import Method (VBA Add-In Object Model) topic in Access' help system for details.

This sample code imported modImportMe.bas from the folder where my database is stored.

Dim strFile As String
Dim strPath As String
Dim strProject As String

strFile = "modImportMe.bas"
strPath = CurrentProject.Path & Chr(92) & strFile
Debug.Print strPath
If Len(Dir(strPath)) > 0 Then
    'VBE.ActiveVBProject.VBComponents.Import strPath
    VBE.VBProjects("Database2").VBComponents.Import strPath
    DoCmd.RunCommand acCmdCompileAndSaveAllModules
Else
    MsgBox "File not found: " & strPath, vbOKOnly + vbCritical, "Oops!"
End If

Note this database actually contains only one VBProject, so I could have referenced it with VBE.ActiveVBProject. However if yours includes more than one VBProject, it's safer to refer to it by name, and VBProjects("<Name>") should work even when there is only one.