使用字符串作为参数调用 VB6



我正在尝试通过使用 CallByName 和遍历对象将某些图像的可见性设置为 false。

这是代码

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

它在"CallByName **theobj_str**..."上抛出错误"类型错误">

CallByName 将对象作为其第一个参数。我需要以某种方式将字符串"theobj_str"转换为对象。我该怎么做?

如果我像这样称呼它,则 CallByName 工作正常:CallByName Images2, "Visible", vbLet,False

谢谢

如果不需要使用 CallByName,则可以遍历控件集合并检查类型。 如果类型与要隐藏的控件匹配,则可以以这种方式设置其可见属性。

代码如下所示:

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

这样做将允许您向窗体添加更多图像控件,而无需记住在 for 循环中更改计数。

希望有帮助。

相关内容

最新更新