我想在Excel中创建一个程序,它循环访问Access数据库列表并编写Access模块中存在的VBA。我找到了一些可以从Access运行的代码,它编写了Access模块中存在的VBA。我试图找出如何从Excel引用数据库文件并在每个数据库文件上运行该程序。我可能会弄清楚如何循环数据库文件。我只需要帮助引用下面代码中的数据库文件。
我可以用这样的东西打开数据库:
Dim cstrDbFile As String = "C:\Database51.accdb"
Dim objShell As Object
Set objShell = CreateObject("WScript.Shell")
objShell.Run cstrDbFile
我还试图像这样建立对Access的引用:
Dim appAccess As Object
Set appAccess = CreateObject("Access.Application")
appAccess.OpenCurrentDatabase ("C:\Database51.accdb")
我需要弄清楚如何在以下位置引用Access数据库:
Application.VBE.ActiveVBProject.VBComponents
我可能需要弄清楚如何创建一个替换ActiveVBProject的引用。
下面是我发现的一些编写VBA模块内容的代码。我不记得我在哪里找到它。
For Each Component In Application.VBE.ActiveVBProject.VBComponents
With Component.CodeModule
'The Declarations
For Index = 1 To .CountOfDeclarationLines
Debug.Print .Lines(Index, 1)
Next Index
'The Procedures
For Index = .CountOfDeclarationLines + 1 To .CountOfLines
Debug.Print .Lines(Index, 1)
Next Index
End With
Next Component
答案 0 :(得分:2)
以下代码将让您看到Access数据库对象,但我不知道如何导出代码(DoCmd不在Excel中?)。你的任务从Access非常简单,所以我会重新考虑......
Option Explicit
' Add a reference to the DAO Object Library
Sub Read_Access_VBA()
Dim dbs As DAO.Database
Dim ctr As DAO.Container
Dim doc As DAO.Document
Dim iC As Integer
Dim iD As Integer
Dim i As Integer
Dim mdl As Module
Set dbs = DBEngine.OpenDatabase("c:\TEMP\106thRoster.mdb", False, False, _
"MS Access;")
Debug.Print "----------------------------------------"
For iC = 0 To dbs.Containers.Count - 1
Debug.Print "Container: " & dbs.Containers(iC).Name
If dbs.Containers(iC).Documents.Count > 0 Then
For iD = 0 To dbs.Containers(iC).Documents.Count - 1
Debug.Print vbTab & "Doc: " & dbs.Containers(iC).Documents(iD).Name
Next iD
Else
Debug.Print " No Documents..."
End If
Next iC
'Set ctr = dbs.Containers!Modules
dbs.Close
Set doc = Nothing
Set ctr = Nothing
Set dbs = Nothing
End Sub
答案 1 :(得分:0)
我找到了一些能帮助我实现最终目标的代码:Exporting MS Access Forms and Class / Modules Recursively to text files?
以下是允许我在项目中取得进展的最重要的一行。
LineCount = oApp.Forms(Name).Module.CountOfLines
FileName = Path & "\" & Name & ".vba"
F = FreeFile
Open FileName For Output Access Write As #F
Print #F, oApp.Forms(Name).Module.Lines(1, LineCount)
Close #F