Importing a module into access programmatically from a *.cls or similar file

荒凉一梦 提交于 2019-12-11 03:02:35

问题


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.



来源:https://stackoverflow.com/questions/31596339/importing-a-module-into-access-programmatically-from-a-cls-or-similar-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!