Setfocus and subforms - 2165 "You can't hide a control that has the focus."
I was quite puzzled. I wanted to setup some fields on my Granite Fleet Manager so that the user could toggle off or on the item cost or price. For example they might want to do up a quote for someone and just show the price. (Hmm, I'll have to add another toggle button to hide the markup.)
To make some fields non visible I had to move the Setfocus elsewhere as otherwise I got error 2165 "You can't hide a control that has the focus.". As these were subforms the quick and dirty approach was to create a control on the main form, set the focus there and then figure out a better solution.
Well that didn't work. Upon much mucking with code figuring things out I was starting to understand what was happening. Close examination of the two fields circled on the form below you can see how they are both slightly highlighted indicating they both have the focus. First time I can recall coming across this interesting concept
Clearly I need to change the focus to a control on the subform. But there are three subforms on that form that could have the cost or the price I want to make non visible. So how do I do that?
Now there might be more elegant solutions but I decided to save a flag value of the subform that I'm making the fields non visible. Then depending on which subform I had the error on I would move the focus to a field just to the left of the fields being hidden.
sbf = 1
Me![Service Detail - Techs sbf].Form![lblCustomerPrice].Visible = Not Me.tglViewPrice
Me![Service Detail - Techs sbf].Form![lblCustomerRate].Visible = Not Me.tglViewPrice
Select Case Err.Number
Case 2165 ' You can't hide a control that has the focus.
Select Case sbf
Me![Service Detail - Techs sbf].Form!srtHours.SetFocus
Me![Service Detail - External Invoices sbf].Form!sriDescription.SetFocus
Me![Service Detail - Parts sbf].Form!ptxQuantity.SetFocus
MsgBox "Tony made a mistake."
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure ViewCostAndPrice of VBA Document Form_Service Detail"
Note that i always place the error text on the error handling line. And sometimes throw in something slightly nonsensical.
I might've used the value of the tab control index and figured out the name then but I felt that was a bit more obscure.