0

I am trying to set some images's visibility to false by using CallByName and a loop through the objects.

here is the code

Private Sub command1Click
dim theobj_str as string
dim ctr as integer
for ctr = 1 to 3
   theobj_str = "Images" & ctr
   CallByName theobj_str, "Visible", vbLet,False
end for
END SUB

It throws an error "TYPE MISMATCH" on "CallByName **theobj_str**..."

The CallByName takes an object as its first argument. I need to somehow convert the string "theobj_str" into an object. How can I do this ?

The CallByName works fine if I call it like : CallByName Images2, "Visible", vbLet,False

Thanks

padjee
  • 125
  • 2
  • 12
  • 2
    `CallByName` requires an object (eg, form, class, etc) as the first argument, the first argument cannot be a string. `CallByName` allows you to access the object's properties and methods indirectly (late-binding, essentially) with a string value. If your object is a form, you can first find the form by searching the forms collection by the form name, then use the form reference as the `CallByName` argument. – MarkL Mar 12 '18 at 11:42
  • I guess i come to a dead end. I will find a new way.thanks mark. – padjee Mar 13 '18 at 11:06
  • Possible duplicate of [How do I use variables to set properties in VBA (Excel)](https://stackoverflow.com/q/5706791/11683) – GSerg Mar 16 '18 at 15:46

1 Answers1

1

If you don't need to use CallByName you could loop through the controls collection and check the type. If the type matches the control you want to hide then you can set it's visible property that way.

The code would look like this:

Private Sub Command_Click()

    SetControlVisibility "Image", False

End Sub

Private Sub SetControlVisibility(ByVal controlType As String, ByVal visibleValue As Boolean)
Dim ctrl As Control

    For Each ctrl In Me.Controls
        If TypeName(ctrl) = controlType Then
            ctrl.Visible = visibleValue
        End If
    Next

End Sub

Doing it this way will allow you to add more image controls to your form without having to remember to change your counts in the for loop.

Hope that helps.

lardymonkey
  • 728
  • 1
  • 16
  • 34