Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA: Why must I set focus to control every time?

I am creating a personal Library Inventory system using an Access 2007 database. In code, whenever I reference the .Text property of a form control, whether it be changing the value, or simply checking the value in an IF statement, I get prompted with Run-time error '2185': You can't reference a property or method for a control unless the control has the focus.

Why is this?

For setting the .Text it's not a huge deal, but when I'm checking the value in an IF statement, I can't set the focus when I'm checking multiple conditions.

like image 913
Analytic Lunatic Avatar asked Jun 25 '13 19:06

Analytic Lunatic


People also ask

What does set focus do in VBA?

The SetFocus method moves the focus to the specified form, the specified control on the active form, or the specified field on the active datasheet.

How do you set focus in access form?

Use the SetFocus method to move the focus to a subform, which is a type of control. You can also move the focus to a control on a subform by using the SetFocus method twice, moving the focus first to the subform and then to the control on the subform.


1 Answers

Use .Value instead - that doesn't require setting focus first. From the documentation, for example for the TextBox control (emphasis mine):

While the control has the focus, the Text property contains the text data currently in the control; the Value property contains the last saved data for the control. When you move the focus to another control, the control's data is updated, and the Value property is set to this new value. The Text property setting is then unavailable until the control gets the focus again.

like image 86
Geoff Avatar answered Sep 28 '22 00:09

Geoff