Avoid repeating code

Catalina

Registered User.
Local time
Today, 11:18
Joined
Feb 9, 2005
Messages
470
I'm trying to make a menu.
Every menu item consists of 3 objects: picture, box and label.

The MouseDown Event of all 3 of these objects has the same code:
(And something similar for the MouseUp Event)

'Change background and border colors
Me.boxNewRecord.BackColor = 7921662
Me.boxNewRecord.BorderColor = 0
'Change picture
Me.imgNewRecordYellow.Visible = True
Me.imgNewRecordBlue.Visible = False
'Label background is transparent so no code needed
..........


So I end up with repeating code for these objects.
Should I move it to a module so I can avoid the repetition,
and if so, how do I call it from my form?

All help will be greatly appreciated.
Catalina
 
if you create a sub in a module and place your code there then all you have to do is on the OnMouseDown event put Call YourSubName
 
In a blank module, you need to have a procedure, either a sub or function. In your case, sub may work adequately, though some people (e.g. me) may elect to use function to verify successful operation.

Either way, it has to be public and callable.

In your case, we're manipulating a control so we need to pass the control as a parameter:

Code:
Public Sub PutNameOfSubHere (MyControl As Control)

MyControl.BackColor =...
MyControl.BorderBorder =....

End Sub

If you elect for a function, you need to return the value:

Code:
Public Function MyFunction()

MyFunction = 0

End Function

HTH.
 
With the form in design view do View-> Code. Then do Insert ->Procedure. Give your new procedure a name, say 'prcMyProc'. The leave the type as 'Sub' and click ok. In code view paste in the following code:

Code:
'Change background and border colors
Me.boxNewRecord.BackColor = 7921662
Me.boxNewRecord.BorderColor = 0
'Change picture
Me.imgNewRecordYellow.Visible = True
Me.imgNewRecordBlue.Visible = False
'Label background is transparent so no code needed

Then in the mouse down event of all three objects simply put the name of your the procedure you want to run. Something like:

Code:
Private Sub Box0_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
prcMyProc
End Sub

Hope this makes sense - :)
 
Thank you all for the quick replies.

For this one I will go with Ken's suggestion, it works great
and the solution is a lot simpler than I thought.

The info about how to use a module will come in handy
at some point, I'm sure.
I learn as I go along.

Thanks again.
Catalina :)
 

Users who are viewing this thread

Back
Top Bottom