Style question: Sharing code between forms

matttsch

New member
Local time
Today, 07:21
Joined
Aug 1, 2007
Messages
4
I am new to Access programming and was giving the job of cleaning up the code of an old project. In this project, there a lot of forms that provide similar functionality using copy-and-paste coding, which I dislike. What is the normal way to handle such cases in Access?

To make things more concrete, here is an example. I have two forms that both have a button that, when pressed, opens a MsgBox into which a user enters the name of a record he would like to search for. If found, the form jumps to that record, otherwise, it ignores the input. Currently, there is identical code in both forms:

Private Sub Search_Click()
recordName = InputBox("Enter Record Name")
filter = "name LIKE '" & recordName & "*'"
Set rs = Me.Recordset.Clone
rs.FindFirst filter
If Not rs.NoMatch Then
Me.bookmark = rs.bookmark
End If
Set rs = Nothing
End Sub

The best idea I have is to create a module with a method like this:

Public Sub Search(theForm as Variant)
recordName = InputBox("Enter Record Name")
filter = "name LIKE '" & recordName & "*'"
Set rs = theForm.Recordset.Clone
rs.FindFirst filter
If Not rs.NoMatch Then
theForm.bookmark = rs.bookmark
End If
Set rs = Nothing
End Sub

and then call that method from both Search_Click event handlers.

Is there a better way? Is there a way to use OO coding to create a common superclass of these two forms and then put the Search code in there? Is there a way to capture the fact that both forms have the same buttons too?

Thanks,
Matt

Details: I'm using a .mdb file in Access 2003
 
You can simply put the code (which should be a function, not a sub) above in a standard module. This is more easier than having it in one form, even if it's public, because Access treat it little differently.

If it's in a standard module, you only need this:

Code:
Call MyPublicFunctionName([i]Arguments[/i])

for whereever you need to fire that function/sub. Remember, you need a function if you want it to return something, a sub if you just need to do something but don't need something in return.

Public sub/functions can be called from a form module but you'd need to do thus:

Code:
Call Forms!MyFormName.MyPublicSubName

In other words, more typing for no reasons.
 

Users who are viewing this thread

Back
Top Bottom