0
votes

In MS Access 2016 I am trying populate a text box on a form, when someone clicks a button on the form.

The button, Command9 - I have set the OnClick event to [Event Procedure], which then created the following:

Private Sub Command9_Click()
End Sub

I added:

Private Sub Command9_Click()
  Me(Field1) = "hello"
End Sub

I also tried:

Private Sub Command9_Click()
  Field1.text = "hello"
End Sub

I get the error:

You can't reference a property or method for a control unless the control has the focus

1
See this answer, use .Value vs .textNapoli

1 Answers

1
votes

There are many, many ways to do this:

The most minimal way, by using the fact that all controls are available as private variables in the form module:

Private Sub Command9_Click()
    Field1= "hello"
End Sub

By using the .Value property to explicitly set the value:

Private Sub Command9_Click()
    Field1.Value= "hello"
End Sub

Using the fact that the controls are available as properties of the form:

Private Sub Command9_Click()
    Me.Field1= "hello"
    'Or Me.Field1.Value = "hello"
End Sub

Using the Form.Controls collection:

Me.Controls("Field1") = "hello"
Me.Controls("Field1").Value = "hello"

Using the bang (!) operator to implicitly use the controls collection:

Me!Field1 = "hello"
Me!Field1.Value = "hello"

All these approaches should reach exactly the same goal.