搜索其他Access数据库中的VBA代码文件

时间:2016-04-11 20:30:30

标签: access-vba ms-access-2013

我在链接How to search through VBA code files中阅读了非常详尽的回复,它对当前项目的效果很好。但是,我只是在打开其他项目并查看代码时感觉很慢。

使用OpenDatabase提到的响应,但我没有看到有关数据库与Application.VBE.ActiveVBProject之间关联的示例。我并没有对此感到懒惰,但是在网上搜索4天已经用尽了我的选择。

任何帮助都会非常感激。

2 个答案:

答案 0 :(得分:1)

道歉。找到其他方法使这项工作。

Public Sub FindWordInOtherModules(ByVal pSearchWord As String, sApplicationFilePath As String)
Dim objComponent As VBComponent
    ' VBComponent requires reference to Microsoft Visual Basic
    ' for Applications Extensibility; use late binding instead:
Dim lStartLine As Long
Dim lEndLine As Long
Dim lStartColumn As Long
Dim lEndColumn As Long
Dim accApp As Access.Application

Set accApp = New Access.Application

With accApp
    .Visible = True
    .OpenCurrentDatabase (sApplicationFilePath)
    .UserControl = True
    'MsgBox .VBE.ActiveVBProject.VBComponents.Count
    'MsgBox .CurrentDb.Name

    For Each objComponent In .VBE.ActiveVBProject.VBComponents
        If objComponent.CodeModule.Find(pSearchWord, lStartLine, lStartColumn, lEndLine, lEndColumn, _
        FindWholeWord, MatchCase, PatternSearch) = True Then
           MsgBox "Found text " & StringToFind & vbCrLf _
               & "Start line: " & lStartLine & vbCrLf _
               & "Line text:  " & objComponent.CodeModule.Lines(lStartLine, lEndLine - lStartLine + 1), vbOKOnly, objComponent.CodeModule.Name
    End If
Next objComponent
End With

accApp.CloseCurrentDatabase
Set accApp = Nothing

End Sub

答案 1 :(得分:0)

您应该添加accApp.Quit:

accApp.CloseCurrentDatabase
accApp.Quit
Set accApp = Nothing

在设置accApp = Nothing以加速关闭应用程序并在执行此代码(Public Sub FindWordInOtherModules)期间,在accApp.Quit行上关闭它,而不是更晚。在我的计算机上,鼠标在执行后几秒仍处于非活动状态,如果没有添加这样的Sub if accApp.Quit。

但是没有必要打开另一个数据库,因为当前数据库只能通过创建临时引用来“链接”它:

Private Sub FindWordInOtherModules2()

Dim objComponent As VBComponent
...
...
Dim lEndColumn As Long

Dim ref As Reference
Dim RefName As String

Const FileName = "C:\Users\....mdb"

With Application 'instead of accApp

    .References.AddFromFile FileName
    '.References.Count because the new one is supposed be the last one (?)
    RefName = .References(.References.Count).Name 

    Dim VBProj As VBProject

    For Each VBProj In .VBE.VBProjects
        If VBProj.FileName <> .CurrentDb.Name Then Exit For
    Next

    For Each objComponent In VBProj.VBComponents
        'Debug.Print objComponent.Name
        ...
        ...
    Next

    Set objComponent = Nothing '?
    Set VBProj = Nothing '?

    Set ref = .References(RefName)
    .References.Remove ref
    Set ref = Nothing '??

End With

End Sub

这似乎比打开另一个数据库文件更快,但无法更新VBA。 References.Remove ref删除引用,但VBA文件夹在左侧面板中仍然可见,并且所有代码都有效,这有点令人不安......

Application.VBE.VBProjects.Remove VBProj不起作用。它可能与“信任中心 - 宏设置”中的“信任访问VBA项目对象模型”选项有关,该选项在Access中不可用。 但是在关闭和打开数据库后项目不可见。