2012-03-08 33 views
3

我将调查许多Acccess应用程序,如果可能的话,这会使我的生活更容易制作脚本。在表单代码模块中查找函数

我的主要目标是通过MS Access表单代码/模块搜索某些单词(例如狗,猫,牛等)并返回包含该单词的模块名称。 (或至少返回,如果它存在与否)

据我了解,内置查找功能不会查找多个单词,只是单个单词。 我不希望把每个单词放在那里,并做一个查找所有,因为这将消耗大量的时间。

你会如何解决这个问题?

如以下回答,正常的模块可以使用查找功能(Module.Find)进行搜索,但它似乎不同于Form.Module。请帮忙!

回答

3

你可以使用类似的东西,但它不会无人值守,因为你可能会遇到各种各样的问题,比如密码等。

重写

这将搜索窗体和报表代码和模块,includimg类模块,但不会搜索注释。

Sub SearchAllCode() 
Dim ap As New Access.Application 
Dim sfile As String, afind As Variant 
Dim mdlname As String, mdl As Object 
Dim prcname As String 
Dim lsline As Long, lscol As Long 
Dim leline As Long, lecol As Long 
Dim sline As String, r As Long 
Dim i, j 

ap.Visible = True 

afind = Split("msgbox,chair,ombo,Visible", ",") 
sfile = Dir("Z:\Docs\*.accdb") 

Do While sfile <> vbNullString 
    ap.OpenCurrentDatabase "Z:\Docs\" & sfile, False, "pass" 

    For i = 1 To ap.VBE.ActiveVBProject.VBComponents.Count 

     Set mdl = ap.VBE.ActiveVBProject.VBComponents(i).CodeModule 

     For j = 0 To UBound(afind) 
      leline = mdl.CountOfLines 
      ''object.Find(target, startline, startcol, endline, endcol 
      ''[, wholeword] [, matchcase] [, patternsearch]) As Boolean 
      ''The default is false for the three optional parameters. 
      ''Finds first occurrence only 
      If mdl.Find(afind(j), lsline, lscol, leline, lecol) Then 

       sline = mdl.Lines(lsline, Abs(leline - lsline) + 1) 
       prcname = mdl.ProcOfLine(lsline, r) 

       Debug.Print mdl.Name 
       Debug.Print prcname 
       Debug.Print lsline 
       Debug.Print sline 
      End If 
     Next 
    Next 
    ap.CloseCurrentDatabase 
    sfile = Dir 
Loop 
ap.Quit 
End Sub 

这是一个替代搜索,但它没有给你提供操纵代码的方法,一旦找到该行。

Sub AlternativeSearch() 
Dim ap As New Access.Application 
Dim sfile As String, afind As Variant 
Dim mdl As Object 
Dim modtext As String, modarray As Variant 
Dim leline As Long 
Dim i, j, k 


ap.Visible = True 

afind = Split("msgbox,chair,ombo,Visible", ",") 
sfile = Dir("Z:\Docs\*.accdb") 

Do While sfile <> vbNullString 
    ap.OpenCurrentDatabase "Z:\Docs\" & sfile, False, "pass" 

    For i = 1 To ap.VBE.ActiveVBProject.VBComponents.Count 

     Set mdl = ap.VBE.ActiveVBProject.VBComponents(i).codemodule 'ap.Modules(mdlname) 
     leline = mdl.CountOfLines 
     modtext = mdl.Lines(1, leline) 

     For j = 0 To UBound(afind) 
      If InStr(modtext, afind(j)) > 0 Then 
       Debug.Print "****" & afind(j) & " found in " & mdl.Name 
       modarray = Split(modtext, vbCrLf) 
       For k = 0 To UBound(modarray) 
        If InStr(modarray(k), afind(j)) > 0 Then 
         Debug.Print k 
         Debug.Print modarray(k) 
        End If 
       Next 
      End If 
     Next 
    Next 
    ap.CloseCurrentDatabase 
    sfile = Dir 
Loop 
ap.Quit 
End Sub 
+0

感谢您的回复!该代码适用于模块中的代码,但是有没有办法通过Form Object代码进行搜索? – James 2012-03-09 03:37:06

+0

您的修改后的代码工作得很好(第二个)。 – James 2012-03-12 02:54:29