more efficient code?

meanster99

Meum cerebrum nocet!
Local time
Today, 11:25
Joined
May 2, 2006
Messages
62
I am a complete newbie to vba and I am sure I end up writing far more code than I need to.

For example I needed to disable all but one control on the oncurrent event of a form and so I wrote:

Me.controlname.Enabled = False
Me.controlname2.Enabled = False
etc
etc

I did this for 13 controls.

Another example

If IsNull(Me.controlname) Or Me.controlname = "" Then
do something
End If

If IsNull(me.controlname2) Or Me.controlname2 = "" Then
do the same thing
End If

etc etc for say 13 more controls.

When I write this I can't help thinking there must be a more efficient way of coding these things in say one or two lines. I am sure there must be a way of referring to multiple controls in one line of code but I don't know what it is!

Can you help me?
 
Thanks for the pointers UG. Will check them out in due course....
 
You can also use the Tag property of the control
ie
Dim ctl As Control
For Each ctl In Me.Controls
If ctl.Tag = "A" Then
If IsNull(Me.pd) Then
End If
If Me.pd = True Then
ctl.Locked = True
ctl.Enabled = False
Else
ctl.Enabled = True
ctl.Locked = False
End If
End If
 
You can also name your controls in a numbered sequence like txt1, txt2, txt3...
and then traverse them like...
Code:
for i = 1 to 13
  if isnull(me.controls("txt" & i)) then
    'do something and use i as a parameter
  end if
next i
check for nulls and other values at the same time using the Nz() function...
Code:
if nz(me.control, "") = "" then
  'if first param in Nz is null, function returns the second param
end if
and you can scrunch this...
Code:
If Me.pd = True Then
ctl.Locked = True
ctl.Enabled = False
Else
ctl.Enabled = True
ctl.Locked = False
End If
to...
Code:
ctl.locked = nz(me.pd, false)
ctl.enabled = not ctl.locked
 
Thanks UG, Rich & Lagbolt - these are exactly the sorts of thing I am after, Cheers guys!
 

Users who are viewing this thread

Back
Top Bottom