Link to home
Start Free TrialLog in
Avatar of Harry Batt
Harry Batt

asked on

Coding a Microsoft Access Form

Is there a better way to handle this...All my continuous forms have the following code in the load event so that they all look have the same look.  In the header section of each form, all my labels are named "Label" with sequential numbers.  The following code works well, with the exception that the Do Until has to be correct for each form so that it is 1 number more than the number of labels. Some forms, such as the one I copied this code from, has 10 labels and some have 3 or 4.  Can this code be modified into a function so that it looks for any control named "LabelX" and assigns it the "lngButtonFont" color? This would help me not have to change the Do Until number in each form.
Thanks experts!
Private Sub Form_Load()
  Dim I As Integer
  Dim lngButtonFont As Long

  lngButtonFont = fGetButtonFont
  
  I = 1
  Do Until I = 11
    Me("Label" & I).ForeColor = lngButtonFont
    I = I + 1
  Loop
   
End Sub

Open in new window

Avatar of Jim Horn
Jim Horn
Flag of United States of America image

>Can this code be modified into a function so that it looks for any control named "LabelX" and assigns it the "lngButtonFont" color?

'This sets the ForeColor for one label named LabelX
Me.LabelX.ForeColor = lngButtonFont

If you still want the loop, and don't want to hard-code the number of labels on each form, and we can assume that all lables have 'Label' in the first five characters of the name, then you could do ...

Dim ctl as Control

For each ctl in Me.Controls
   If left(ctl.Name, 5) = "Label" then
      ctl.ForeColor = lngButtonFont
   End If
Next
(or come to think of it)

If TypeOf(ctl) Is Label
  'code goes here
End If
Avatar of Harry Batt
Harry Batt

ASKER

Jim,

Can you tell me what is wrong with this code? It doesn't work
Function fLoadForm()
    Dim ctl As control
    Dim lngButtonFont As Long

   
    lngButtonFont = fGetButtonFont

    If TypeOf ctl Is label Then
        ctl.ForeColor = lngButtonFont
    End If

End Function

Open in new window

I believe Jim meant for you to just replace the IF portion.  You still need the For..Next loop.
ASKER CERTIFIED SOLUTION
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial