ACC97: How to Programmatically Create, Search, Replace, and Modify Code

ID: Q187318


The information in this article applies to:


SUMMARY

Moderate: Requires basic macro, coding, and interoperability skills.

This article describes and gives you examples of how to programmatically create, search, replace, and modify Visual Basic for Applications code within Microsoft Access 97.

One of the most common uses for code that itself writes code is a wizard. Wizards can be used to offer a variety of solutions that do not require the user to understand, or to have access to, product-development features. For example, a wizard can be used to create custom toolbars and menu bars that meet specific user requirements.


MORE INFORMATION

Determining what code to write based on your users' requirements will be left up to you, the application designer. This article will concentrate on taking the desired code and creating a new subroutine in a new module. It will then go on to demonstrate how to manipulate the code that has just been created. Microsoft provides programming examples for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability and/or fitness for a particular purpose. This article assumes that you are familiar with the programming language being demonstrated and the tools used to create and debug procedures. Microsoft support professionals can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific needs. If you have limited programming experience, you may want to contact a Microsoft Certified Solution Provider or the Microsoft fee-based consulting line at (800) 936-5200. For more information about Microsoft Certified Solution Providers, please see the following page on the World Wide Web:

http://www.microsoft.com/mcsp/
For more information about the support options available from Microsoft, please see the following page on the World Wide Web:

http://www.microsoft.com/support/supportnet/overview/overview.asp

How to Create a Subroutine in Code
----------------------------------

This example creates a new module, inserts the code for a working
subroutine, and then saves, closes, and renames the module.

The code in this example inserts the following subroutine in a module
called Create Code:

   Sub TestOpenDatabase()
       Dim DB As Database
       Set DB = CurrentDb
       MsgBox "The Database " & DB.Name & " opened successfully!"
       DB.Close
   End Sub

  1. Create a new module and name it "Create Code."

  2. In the Create Code module, insert the following lines of code:

       Option Compare Database
       Option Explicit
          Dim MyModule As Module

       Sub CreateCode()

          Dim strIndent As String, strText As String

          ' Create 4 spaces for code indent.
          strIndent = "    "

          ' Build a string variable with the code to be written
          ' to the new module.
          strText = "Sub TestOpenDatabase()" & vbCrLf
          strText = strText & strIndent & "Dim DB As Database" & vbCrLf
          strText = strText & strIndent & "Set DB = CurrentDB" & vbCrLf
          strText = strText & strIndent & "MsgBox ""The Database "" & " & _
             "DB.Name & "
          strText = strText & strIndent & strIndent & """ opened " & _
             "successfully!""" & vbCrLf
          strText = strText & strIndent & "DB.Close" & vbCrLf
          strText = strText & "End Sub"

          ' Create a new Module.
          Application.RunCommand acCmdNewObjectModule

          ' Set MyModule to be the new Module Object.
          Set MyModule = Application.Modules(Application.CurrentObjectName)

          ' Insert the code string into the new module.
          MyModule.InsertText strText

          ' Save, close, and rename the new Module as "Created Code."
          DoCmd.Save acModule, MyModule
          DoCmd.Close acModule, MyModule, acSaveYes
          DoCmd.Rename "Created Code", acModule, MyModule

       End Sub

  3. With the pointer anywhere within the CreateCode subroutine, press F5
     to run the code.

  4. To see the TestOpenDatabase subroutine just created, open the
     Created Code module.

  5. On the Tools Menu, click References, ensure that the Microsoft DAO 3.5
     Object Library check box is selected, and then click OK.

  6. Run the TestOpenDatabase subroutine.

NOTE: You cannot have multiple modules or subroutines with the same name.
Before you run the code in this example a second time, delete the module
Create Code.

How to Search for a Code String in a Module
-------------------------------------------

This example uses the Find method to locate a string in a module.

Because the Find method is not aware of where any subroutine starts or
ends, and because there may be multiple copies of the string you are
searching for in the module, you must take care in selecting the correct
string. Once the Find method locates the string, it returns the string's
line number within the module.

If you wanted to search for a string within a specific subroutine within a
module, you could:

   A. Use the Find method to locate and save the line number for the first
      instance of the name of a specific subroutine.

   B. Use the Find method to locate and save the line number of the
      first instance of the string "End Sub" starting at the line number
      captured in step A by using Find's startline argument.

   C. Use the Find method to locate and save the line number of the
      string you are searching for within the desired subroutine by
      specifying the startline from step and the endline from step
      B by using Find's startline and endline arguments.

In the Find method, the target, startline, startcolumn, endline, and
endcolumn arguments are not optional and are updated to the matching string
values when Find locates the string. For more information, please see
Microsoft Access Help for additional Find method arguments.

In this example, the code searches the module created in the previous
example for the string "DB.Close" and inserts the line of code, "Set DB =
Nothing" on the following line. It will then save and close the Created
Code module.

  7. Open the Create Code module and insert the following lines after the
     code created in the previous example:

     Sub SearchCode()
       Dim StartLine As Long, StartColumn As Long
       Dim EndLine As Long, EndColumn As Long

       ' Open the Module you want to modify.
       DoCmd.OpenModule "Created Code"

       ' Set the Created Code Modules as the Object.
       Set MyModule = Application.Modules("Created Code")

       ' Search for string "DB.Close".
       If MyModule.Find("DB.Close", StartLine, StartColumn, _
          EndLine, EndColumn) Then

          ' If string is found, insert new line of code using the same
          ' column indent.
          MyModule.InsertLines StartLine + 1, _
             String(StartColumn - 1, " ") & "Set DB = Nothing"
       Else
          MsgBox "Text not found."
       End If

       ' Save and close the module.
       DoCmd.Save acModule, MyModule
       DoCmd.Close acModule, MyModule, acSaveYes

     End Sub

  8. With the pointer anywhere within the SearchCode subroutine, press F5
     to run the code.

  9. To see the TestOpenDatabase subroutine just created, open the
     Created Code module.

 10. Run the subroutine TestOpenDatabase.

How to Replace a Line of Code in a Module
-----------------------------------------

This example uses the Find method to locate the string "Set DB =" and
replaces the entire line of code with the following two lines:

   "Set DB = DBEngine.OpenDatabase("C:\Program Files\Microsoft Office\" & _
       "Office\Samples\Solutions.mdb")"

This example requires that the Solutions.mdb database is in the location
specified in the preceding line. If this is not the case, modify the
example below to point to a valid database path and file.

  11. Open the Create Code module and insert the following lines after the
      code created in the previous example:

      Sub ReplaceCode()
        Dim StartLine As Long, StartColumn As Long
        Dim EndLine As Long, EndColumn As Long

        ' Open the Module you want to modify.
        DoCmd.OpenModule "Created Code"

        ' Set the Created Code Modules as the Object.
        Set MyModule = Application.Modules("Created Code")

        ' Search for string "Set DB =".
        If MyModule.Find("Set DB =", StartLine, StartColumn, EndLine, _
           EndColumn) Then

          ' If string is found, insert new line of code using the same
          ' column indent.
          MyModule.ReplaceLine StartLine, String(StartColumn - 1, " ") & _
             "Set DB = DBEngine.OpenDatabase(""C:\Program Files\" & _
             "Microsoft Office\"" & _" _
             & vbCrLf & "        ""Office\Samples\Solutions.mdb"")"

        Else
          MsgBox "Text not found."
        End If

        ' Save and close the module.
        DoCmd.Save acModule, MyModule
        DoCmd.Close acModule, MyModule, acSaveYes

      End Sub

  12. With the pointer anywhere within the ReplaceCode subroutine, press F5
      to run the code.

  13. To see the TestOpenDatabase subroutine just created, open the
      Created Code module.

  14. Run the TestOpenDatabase subroutine.

How to Modify a Line of Code in a Module
----------------------------------------

This example uses the Find method to locate the string "Solutions.mdb" and
to replace it with "Northwind.mdb".

To accomplish this, the code has to disassemble the located line of text,
remove the old string, and reconstruct the line with the new string. As
before, it will save and close the module after making the changes.

This example requires that the Solutions.mdb and Northwind.mdb databases
are in the location specified in the preceding example. If this is not the
case, modify the example below to point to valid database paths and files.

  15. Open the Create Code module and insert the following lines after the
      code created in the previous example:

      Sub ModifyCode()
         Dim StartLine As Long, StartColumn As Long
         Dim EndLine As Long, EndColumn As Long
         Dim strLine As String, strNewLine As String
         Dim intChr As Integer, intBefore As Integer, intAfter As Integer
         Dim strLeft As String, strRight As String
         Dim strSearchText As String, strNewText

         ' The string you are searching for is:
         strSearchText = "Solutions.mdb"

         ' The replacement string is:
         strNewText = "Northwind.mdb"

         ' Open the Module you want to modify.
         DoCmd.OpenModule "Created Code"

         ' Set the Created Code Modules as the Object.
         Set MyModule = Application.Modules("Created Code")

         ' Search for string.
         If MyModule.Find(strSearchText, StartLine, StartColumn, EndLine, _
            EndColumn) Then

          ' Store text of line containing string.
          strLine = MyModule.Lines(StartLine, Abs(EndLine - StartLine) + 1)

          ' Determine length of line.
          intChr = Len(strLine)

          ' Determine number of characters preceding search text.
          intBefore = StartColumn - 1

          ' Determine number of characters following search text.
          intAfter = intChr - CInt(EndColumn - 1)

          ' Store characters to left of search text.
          strLeft = Left$(strLine, intBefore)

          ' Store characters to right of search text.
          strRight = Right$(strLine, intAfter)

          ' Construct string with replacement text.
          strNewLine = strLeft & strNewText & strRight

          ' Replace the original line.
          MyModule.ReplaceLine StartLine, strNewLine

         Else
            MsgBox "Text not found."
         End If

         ' Save and close the module.
         DoCmd.Save acModule, MyModule
         DoCmd.Close acModule, MyModule, acSaveYes

      End Sub

  16. With the pointer anywhere within the ModifyCode subroutine, press F5
      to run the code.

  17. To see the TestOpenDatabase subroutine just created, open the
      Created Code module.

  18. Run the subroutine TestOpenDatabase. 


REFERENCES

For more information about the searching for, inserting, or replacing of lines of code, search the Help Index for "Find Method," "InsertText Method," "ReplaceLine Method," and "Lines Property."

Additional query words: inf


Keywords          : kbdta AccCon GnlFnd PgmHowto KbVBA 
Version           : WINDOWS:97
Platform          : WINDOWS 
Issue type        : kbhowto 

Last Reviewed: July 6, 1999