Link to home
Start Free TrialLog in
Avatar of xerle
xerle

asked on

Testing for the existence of an ActiveControl

If you use aForm.ActiveControl or Screen.ActiveControl when there isn't one, an error occurs.  How do test for the presence of an active control before trying to refer to it?
Avatar of Markus Fischer
Markus Fischer
Flag of Switzerland image

Hello,

The standard answer for that is "use error management", I guess:

Sub TestThis()

    Dim ctl As Control

On Error Goto TestThis_Error

    Set ctl = Screen.ActiveControl

    ' [...]

TestThis_Exit:

    Exit Sub

TestThis_Error:

    If Err.Num = <insert number here> Then
        ' take propert action, e.g.
        Resume TestThis_Exit
    ElseIf Err.Num = ....
        ' ...
    End If
    MsgBox Err.Description, , "Error " & Err.Num
    Resume TestThis_Exit

End Sub

You code should have this anyway ;)

Cheers!
(°v°)
ASKER CERTIFIED SOLUTION
Avatar of Markus Fischer
Markus Fischer
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of xerle
xerle

ASKER

Harfang,

I modified your last suggestion a little as follows:

   Function ActiveControlExists(aForm As Form) As Boolean

       'Test for the existence of a valid ActiveControl.

       On Error GoTo HandleErr

       Dim aControl As Control
       Set aControl = aForm.ActiveControl
       ActiveControlExists = True

       Exit Function

   HandleErr:
       ActiveControlExists = False

   End Function


Thanks,
Erle
Sure, looks good. ;)

Probably not important, but an error handler should end with either a Resume. clearing of the error, or raising a new one...

   HandleErr:
       ActiveControlExists = False
       Err.Clear   ' <--- added

   End Function

But again, I'm not sure this makes any difference...

Happy programming!
(°v°)