Obtaining textbox value in change event handler
ms-access, vba
Solution
I know this is an old thread but it's the first I found when I had the same problem. None of the answers helped except Kaganar's own solution, which pointed me in the right direction. I'm guessing the reason people had trouble reproducing the error is there are some important details missing from Kaganar's description:
- The Textbox was in the form header (or footer).
- The form did not allow additions.
Because I believe the full answer is...
The Text property of any control is inaccessible when the form has a record source with no records to edit
I think there is part of Access that does not realise the textbox exists :) To understand how that might come about...
- Put the unbound TextBox in the detail of the form
- Do not allow additions
- Set the recordsource to return no records
- Open the form.
Hey presto! No Textbox.
Return a record, or allow additions, or delete the recordsource, et Voila! There is your Textbox with it's Text.
Problem
I've written a form that performs queries asynchronously as text is typed into a textbox, however I somewhat arbitrarily seem to get the following error thrown: "You can't reference a property or method for a control unless the control has focus." The immediately relevant code is: ``` Dim UpdateRequested As Boolean Dim qryText As String . . . Private Sub txtBox_Change() qryText = txtBox.Text UpdateRequested = true End Sub ``` Some place in the ellipses is the code that handles dynamically loading an ADODB record set, populating a local table, and refreshing a sub form. However, even when I disable this code, the problem persists: Sometimes I get the error. Sometimes I do not. This seems to be persistent through closing the database and reopening it. Every time it starts working again, it's because I've been fooling around with code in the debugger, but I'm not sure what exactly is causing it to magically "just work" or what is causing it to not work at all. Update Just to make things more puzzling, I added a couple of simple event handlers: ``` Private Sub txtBox_GotFocus() MsgBox "Got focus" End Sub Private Sub txtBox_LostFocus() MsgBox "Lost focus" End Sub ``` I run the form. I click in the test box. I receive the "Got focus" message. As soon as I type I see the error as described above. If I re-open the form, I can click between the text box in question (which itself is unbound) and a bound text box in the sub form and see both "Got focus" and "lost focus" messages as one would expect. Furthermore, showing a message box with the current value of "Screen.ActiveControl.Name" shows the expected name just before the Text property is accessed.