Referring to Forms objects using variables

grahamvb

Registered User.
Local time
Yesterday, 21:14
Joined
Aug 27, 2013
Messages
57
Hello Access-Programmers,

I have a simple date stamp that works great in a private sub within a form. (error handling removed for clarity)

Code:
Private Sub btnDateStamp_Click()
 
'    UserInit is global variable
 
    Me!Notes.SetFocus
 
    Me!Notes = Chr$(13) & Date & " - " & Time() & " - " & UserInit & _
        " -" & vbCrLf & Me!Notes
 
    Me!Notes.SelStart = (Len(Me!Notes) - (Len(Me!Notes) _
        - Len(Date) - Len(Time) - Len(UserInit) - 9))
 
End Sub

I am rewriting it as Module function that is Called from various forms, to save space. The function receives the parameters varFormName and varControlName. I wish to write the results of the function back to a memo field on the form.

I am stumped at the get go by the need to refer to the Forms controls with a full reference instead of the Me command.

Code:
Function DateStamp(varFormName As String, varMemoName As String)
 
'varInitials, varFormName, varMemoName are global variables
 
Forms!varFormName.Controls!varMemoName.SetFocus ' [COLOR=red]Error here[/COLOR]
 
'Me!Notes = Chr$(13) & Date & " - " & Time() & " - " & varInitials & _
'    " -" & vbCrLf & Me!Notes
 
'Me!Notes.SelStart = (Len(Me!Notes) - (Len(Me!Notes) _
'    - Len(Date) - Len(Time) - Len(varInitials) - 9))
 
End Function

I think once I understand how to refer to the forms control's with their full reference, from within the Module's function, the rest will fall into place.

Thanks for any help.
 
The SetFocus line isn't needed, but off the top of my head:

Forms(varFormName).Controls(varMemoName).SetFocus
 
Thanks, that is exactly what I needed!

(Without the SetFocus there is error 2185, You can't reference a property or method for a control unless the control has the focus.)
Because the user clicks a Date Stamp button next to the memo field, the button has focus when the function executes.

Here is the finished product.
A Module level date stamp function for any memo on any form in your project.

Code:
Function DateStamp(varFormName As String, varMemoName As String)
 
'varInitials, varFormName, varMemoName are global variables
Forms(varFormName).Controls(varMemoName).SetFocus
 
    Forms(varFormName).Controls(varMemoName) = Chr$(13) & Date & " - " & Time() & varInitials & _
    " - " & vbCrLf & Forms(varFormName).Controls(varMemoName)
 
    Forms(varFormName).Controls(varMemoName).SelStart = (Len(Forms(varFormName).Controls(varMemoName)) _
    - (Len(Forms(varFormName).Controls(varMemoName)) - Len(Date) - Len(Time) - Len(varInitials) - 8))
 
End Function
 
Happy to help! I didn't notice the SelStart in there, and it requires focus, so I stand corrected. Normally it's not needed.
 

Users who are viewing this thread

Back
Top Bottom