How to use a variable to replace the name of a form in VBA code

  • Thread starter Armand via AccessMonster.com
  • Start date
A

Armand via AccessMonster.com

I would like to use the same code to execute on events of several forms.
I would like to be able to use the name of the Form as a variable in my code
so the code could adapt it self to the form.

Ex:

Function x ([Name of the form] as ?)

'my code...
[Name of the form]!Controlx.enabled = true
'my code...

End Function

I tryed to declare the form as an object and replace the name of the form by
the name of the object but it doesn't work.

Anyone could help?
 
A

Armand via AccessMonster.com

At the end, declaring the name of the form as object, it works. sorry
 
B

Brendan Reynolds

You can do it either way (name as string, form as object). Here are examples
of each ...

Public Sub PassFormNameAsString()

Dim strFormName As String
strFormName = "frmTest"
TakeFormNameAsString strFormName

End Sub

Public Sub TakeFormNameAsString(strFormName As String)

If Not CurrentProject.AllForms(strFormName).IsLoaded Then
DoCmd.OpenForm strFormName
End If
Forms(strFormName)!lblTest.Caption = "Called As String"

End Sub

Public Sub PassFormAsForm()

Dim frm As Form

If Not CurrentProject.AllForms("frmTest").IsLoaded Then
DoCmd.OpenForm "frmTest"
End If
Set frm = Forms("frmTest")
TakeFormAsForm frm

End Sub

Public Sub TakeFormAsForm(frm As Form)

frm!lblTest.Caption = "Called As Form"

End Sub
 
R

Ron Weiner

If the routine is not going to return a value use a Sub instead of a
Function. Here is an example where you would pass the form object to the
sub. Put this code in a Module and notice it is declared as a Public Sub.
This makes it available from anywhere in your project.

Public Sub YourSub(frmForm As Access.Form)

' Intro code
frmForm!YourControl.Enabled = True
' Outro Code
End Sub

You'd call it from your form like this:

YourSub Me.Form
or alternately
Call YourSub(Me.Form)

If the routine does have to return a value you want to use a function which
might look like this:

Public Function YourFunction(frmForm As Access.Form) as Long
Dim SomeValueThatWasCalculatedHere as Long

' Intro code
frmForm!YourControl.Enabled = True
' Outro Code
' Return a long value that was calculated above
YourFunction = SomeValueThatWasCalculatedHere
End Function

and you'd call it from your form like this:

MyLongResult = YourFunction(Me.Form)
 
Top