2012-03-08 30 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