Blacksmith
Blacksmith

Reputation: 37

How to determine the Object Type from the field name in a form?

I am trying to generalize this Sub. The sub works, without the test for the checkbox, for text fields. A checkbox has no .BackStyle nor a .ForeColor property.

I tried the code below:

Private Sub EnableEdit(strFieldname As String, Optional bUseRed As Boolean = False)
    Me.Controls(strFieldname).Enabled = True
    Me.Controls(strFieldname).Locked = False
    If Not(TypeOf (Me.Controls(strFieldname)) Is CheckBox) Then
        Me.Controls(strFieldname).BackStyle = 1
        If bUseRed Then
            Me.Controls(strFieldname).ForeColor = vbRed
        Else
            Me.Controls(strFieldname).ForeColor = vbBlack
        End If
    End If
End Sub

However

If Not(TypeOf (Me.Controls(strFieldname)) Is CheckBox) Then

is not syntactically correct. TypeOf expects an object and Me.Controls(strFieldname) is the control itself.

I tried alternative ways for Me.Controls(strFieldname).

https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/early-late-binding/determining-object-type

Upvotes: 0

Views: 1182

Answers (2)

FaneDuru
FaneDuru

Reputation: 42256

The line If Not(TypeOf (Me.Controls(strFieldname)) Is CheckBox) Then has a problem:

  1. The correct syntax would be:
If Not TypeOf Me.Controls(strFieldname) Is CheckBox Then

Upvotes: 0

Erik A
Erik A

Reputation: 32682

If you're using standard Access controls, the easiest way is just to access the ControlType property

If Not Me.Controls(strFieldname).ControlType = acCheckbox Then

For special controls, TypeOf can be beneficial. You need to specify the class, which is likely Access.Checkbox (msforms.Checkbox can be used in Access as well but is very unusual).

If Not TypeOf Me.Controls(strFieldname) Is Access.Checkbox Then

The main source of your error, by the way, is the excessive use of parentheses. If you surround an object with parentheses, you get its default property:

Me.Controls("MyCheckbox") 'A checkbox

(Me.Controls("MyCheckbox")) 'The value of a checkbox

Upvotes: 3

Related Questions