VBA Controls Class

dbote
dbote used Ask the Experts™
on
A UserForm for my MS Word  document has a button click that loops through the Controls on the form.

Private Sub cmdBack_Click()
  Dim ctrl As Control
  For Each ctrl In frmTest.Controls    
        If ctrl.Name = "fra1" Then ctrl.Visible = False
  Next
End Sub

Stepping through everything seems to work great BUT the control named fra1 never goes invisible.

In the Immediate window the control referenced with ctrl.visible returns False while the control referenced with fra1.visible returns True

If I change the code to fra1.visible = False the control does become invisible.

Why are these two code segments getting different results?

Thank you,

dbote
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Chris BottomleySoftware Quality Lead Engineer
Top Expert 2011

Commented:
Is it finding that control on the form frmtest? ... try changing ctrl.visible = false to msgbox "here"

Chris

Author

Commented:
In the For Each loop the control is definitely being found.  During debug I have cycled through stopping with each control and the control named fra1 definitely exists and is being found.
Chris BottomleySoftware Quality Lead Engineer
Top Expert 2011

Commented:
fra1 would work irrespective of caps whereas the name check would fail depending on vcase of the name ... so is the name definitely lower case?

Chris
Commented:
Since there appeared to be two controls with the same name I started thinking.  The only way that could happen was if there was a second form because two controls with the same name can not be on the same form.  I believe because I was referencing the form by name it actually created a new form with that name.  I changed the frmTest to Me and it worked.

I changed the code to the following.

Private Sub cmdBack_Click()
  Dim ctrl As Control
  For Each ctrl In Me.Controls    
        If ctrl.Name = "fra1" Then ctrl.Visible = False
  Next
End Sub

Author

Commented:
I'm hoping that other will learn from my "mistake".

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial