Passing a form name to a public sub

User avatar
silverback
5StarLounger
Posts: 780
Joined: 29 Jan 2010, 13:30

Passing a form name to a public sub

Post by silverback »

I am trying to create a public subroutine which checks form controls but can be called from event handlers behind three different forms.

I've found out that I can declare a variable of type Form, so I'm trying to use such a variable to pass the name of the form which caused the event into the public subroutine which is declared as

Public Sub subname(FormName as Form)

in the hope that I could then be able to check the controls using code like FormName!<controlname>

I haven't got that far, because the calling code is failing; I've tried subname(Me.Parent!SubFormName) which gave a Error 13 - Type Mismatch, and then I tried declaring a variable of type Form and assigning the form to it (Dim frmFormName as Form frmFormName = Me.Parent!<subformname>), which generated a Compile Error - Invalid use of Property.

I don't want to write three individual utility routines (one for each form that needs to perform the checks), so what do I need to do to write the public sub to use general code which doesn't need to know which form called it, and how do pass the name of the calling form into it, please?

Thanks
Silverback

User avatar
HansV
Administrator
Posts: 78588
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Passing a form name to a public sub

Post by HansV »

You don't really have to pass the name. You can use CodeContextObject to refer to the form or report from which the code is called.

Example:

Code: Select all

Public Sub subname()
  Dim ctl As Control
  For Each ctl In CodeContextObject.Controls
    If ctl.ControlType = acTextBox Then
      ...
    End If
  Next ctl
End Sub
Best wishes,
Hans

User avatar
silverback
5StarLounger
Posts: 780
Joined: 29 Jan 2010, 13:30

Re: Passing a form name to a public sub

Post by silverback »

Hans
Thanks for this; it makes checking the controls very easy.
However, there is a need to refer explicitly to some of the controls e.g. Salary because the routine has to perform a calculation to scale the salary depending on hours worked. I'm using CodeContextObject in a loop (as you showed above) to check whether any of the required fields is null, but how do I explicity refer to a field like NumberofHours?
Thanks
Silverback

User avatar
HansV
Administrator
Posts: 78588
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: Passing a form name to a public sub

Post by HansV »

You can use either

CodeContextObject!NumberOfHours

or

CodeContextObject.Controls("NumberOfHours")
Best wishes,
Hans

User avatar
silverback
5StarLounger
Posts: 780
Joined: 29 Jan 2010, 13:30

Re: Passing a form name to a public sub

Post by silverback »

Many thanks, again. Everything's working OK, now
Silverback