0

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

Community
  • 1
  • 1
Mark Tait
  • 545
  • 3
  • 12
  • 22
  • 1
    See [this answer](https://stackoverflow.com/questions/17306200/vba-why-must-i-set-focus-to-control-every-time), use `.Value` vs `.text` – Napoli Mar 08 '18 at 13:59

1 Answers1

1

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.

Erik A
  • 31,639
  • 12
  • 42
  • 67