【问题标题】:Add Reference Library to an outside MS Access Database将参考库添加到外部 MS Access 数据库
【发布时间】:2020-05-31 03:32:29
【问题描述】:

我有一个创建新 MS Access 数据库的代码。我想将参考库添加到这些新创建的 MS Access 数据库中。 这是我编写但无法正常工作的代码:

Sub makeDb(fl As String)    
Dim fs
Set fs = CreateObject("Scripting.FileSystemObject")

'check if the file already exists

If fs.FileExists(fl) = False Then

    'create new ms access database

    Dim accessApp As Access.Application
    Set accessApp = New Access.Application
    accessApp.DBEngine.CreateDatabase fl, dbLangGeneral

    'loop through all references in current database and add them to the newly created dbs

    Dim cur_vbProj As VBIDE.VBProject: Set cur_vbProj = Application.VBE.VBProjects(1)
    Dim cur_vbRefs As VBIDE.References: Set cur_vbRefs = cur_vbProj.References
    Dim cur_vbRef As VBIDE.Reference

    For Each cur_vbRef In cur_vbRefs
        Dim cur_guid As String: cur_guid = cur_vbRef.Guid
        Dim cur_major As Long: cur_major = cur_vbRef.Major
        Dim cur_minor As Long: cur_minor = cur_vbRef.Minor

        'here is the code that doesn't work

        Dim vbProj As VBIDE.VBProject: Set vbProj = accessApp.Application.VBE.VBProjects(1)
        Dim vbRefs As VBIDE.References: Set vbRefs = vbProj.References
        vbRefs.AddFromGuid Guid:=cur_guid, Major:=cur_major, Minor:=cur_minor

    Next

    accessApp.Quit
    Set accessApp = Nothing

End If

End Sub

Set vbProj = accessApp.Application.VBE.VBProjects(1) 行抛出运行时错误“9”下标超出范围。我应该如何修改代码?是否可以添加对外部数据库的引用?

【问题讨论】:

  • 我不知道您的问题的答案,但是 1)您可以尝试 VBProjects(0) 以防它是从零开始的,2)您可以提前创建一个模板数据库(设置为根据需要引用),并复制模板数据库而不是创建一个新的
  • 另一种方法是修改代码以使用后期绑定,然后不需要选择库。
  • 这感觉就像XY Problem。为什么要动态创建 Access 数据库项目?如果需要分发具有相同应用程序代码(带有库)的前端副本,为什么不直接在文件系统级别复制当前的 Access 数据库?
  • 我需要它,因为它是工作要求。 Ppl 不能使用可以更好地处理大型数据集的 SAS EG。他们希望我将数据放入 MS Access。如果我只是按照建议复制过去几个月的数据库,那么我需要清空所有表,并压缩数据库。这是我目前正在使用的解决方案,但我不喜欢它。我正在寻找更好的选择。
  • 为什么不在同一个数据库中有多个月份?

标签: vba ms-access


【解决方案1】:

以下作品适合我:

Sub makeDb(f1 As String)
Dim accApp As Access.Application
Dim cur_vbRefs As References
Dim cur_vbRef As Reference
If Dir(f1) = "" Then
    Access.DBEngine.CreateDatabase f1, dbLangGeneral
    Set accApp = New Access.Application
    accApp.OpenCurrentDatabase f1
    'loop through all references in current database and add them to the newly created dbs
    Set cur_vbRefs = Application.References
    For Each cur_vbRef In cur_vbRefs
        On Error Resume Next
        accApp.References.AddFromGuid cur_vbRef.Guid, cur_vbRef.Major, cur_vbRef.Minor
    Next
End If
End Sub

【讨论】:

  • 工作。您如何使新数据库受信任?
  • 另一个问题的主题。我从来没有为此探索过 VBA。
猜你喜欢
  • 1970-01-01
  • 2017-11-20
  • 1970-01-01
  • 2013-01-12
  • 2023-03-06
  • 2013-04-28
  • 1970-01-01
  • 2018-01-30
  • 2016-09-14
相关资源
最近更新 更多