Reading control value from Public Function in Module?

grahamvb

Registered User.
Local time
Today, 12:41
Joined
Aug 27, 2013
Messages
57
Hello Access-Programmers,

I am trying to read the value of a control on an open form from a Public Function in a Module with no luck. I suspect the issue is syntax.
Code:
Public Function MyFunction(varFormName As String, varControlName As String)
 
If Forms(varFormName).Controls(varControlName) = True Then [COLOR=seagreen]' = 0 even when control is -1[/COLOR]
Else
End If
 
End Function
The variables pass through fine but the If statement equals zero regardless of the state of the form’s control. I tried several variations to no avail.

If Forms(varFormName).Form.Controls(varContactControl) = True Then
If Forms(varFormName)!Form.Controls(varContactControl) = True Then
Etc.

Any help on getting this right is greatly appreciated.
 
Check your values maybe? Just tested this:

Code:
Public Function MyFunction(varFormName As String, varControlName As String)
  Debug.Print Forms(varFormName).Controls(varControlName).Value
  If Forms(varFormName).Controls(varControlName) = 123 Then    ' = 0 even when control is -1
    Debug.Print True
  Else
    Debug.Print False
  End If
End Function

Called like:

MyFunction "form1", "text12"

with the textbox containing 123 and the debug results were:

123
True
 
The Value property of a control is only updated after the focus leaves the control. If what is showing in the control is required prior to this update then use the Text property of the control.

BTW. You can pass the control object itself rather than its name and parent form name if that suits your purposes.

Public Function MyFunction(ctrl As Access.Control)
If ctrl = 123
etc

Called from the form as:
whatever = MyFunction(Me.controlname)
 
Many thanks to both of you. The issue turned out to be an error in the control name (calling the function with the wrong control variable) from the control's On Click event. It works like a charm now.

Thanks again!
 

Users who are viewing this thread

Back
Top Bottom