• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 376
  • Last Modified:

(easy) Accessing a form field value in VBA

I have a form (frmCMReport) with two text fields (txtCMStartDate, txtCMEndDate) and a button.

Code when you click the button:

Private Sub cmdRunReport_Click()
    Dim retVal As Integer
    Dim myStr As String
    myStr = "start: "
    myStr = myStr & frmCMReport.txtCMStartDate.Text    ' error line
    myStr = myStr & ", end: "
    myStr = myStr & frmCMReport.txtCMEndDate.Text
    myStr = myStr & "."
    retVal = MsgBox(myStr, vbOKOnly)
End Sub

(It's just simple code to display the values as I want to know how to access the field values. Doing stuff with them comes later.)

Right now when I run the code I get "Error 424 Object Required". If I change the error line to "myStr = myStr & Form_frmCMReport.txtCMStartDate.Text" I get "Error 2185 You can't reference a property or method for a control unless the control has the focus".

This should be a simple thing to do, so how do I do it?
0
asswasp
Asked:
asswasp
  • 2
1 Solution
 
dannywarehamCommented:
What is "frmCMReport.txtCMStartDate"?
If this code is being ran from the form, you can just use:
me.txtCMStartDate
Also, lose the .text - it's not needed

Private Sub cmdRunReport_Click()
    Dim retVal As Integer
    Dim myStr As String
    myStr = "start: "
    myStr = myStr & me.txtCMStartDate   ' error line
    myStr = myStr & ", end: "
    myStr = myStr & me.txtCMEndDate
    myStr = myStr & "."
    retVal = MsgBox(myStr, vbOKOnly)
End Sub


If it still gives you a prob, change the focus in the code:

Private Sub cmdRunReport_Click()
    Dim retVal As Integer
    Dim myStr As String
    myStr = "start: "
me.txtCMStartDate.setfocus
    myStr = myStr & me.txtCMStartDate   ' error line
    myStr = myStr & ", end: "
me.txtCMendDate.setfocus
    myStr = myStr & me.txtCMEndDate
    myStr = myStr & "."
    retVal = MsgBox(myStr, vbOKOnly)
End Sub
0
 
asswaspAuthor Commented:
Your first version works perfectly. Thank you!
0
 
dannywarehamCommented:
Just a note - if you're referencing an object (text box etc) on the form that your code is running on, you don't need to put the form name on.
If you type ME. when you press . you'll get a list of your objects.

:-)
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now