将 parent 控件设置为另一个控件

Set parent Control to another control

我需要使用 VBA 代码将 parent 控件设置为另一个控件。 实际上我正在循环动态地创建不同的控件,我现在想 link 它们 child-parent。

有人有想法吗?

您在问题中提供的信息太少,很难猜出您的 objective。

但是,我猜你想记录控件 Xxxxx 是控件 Yyyyy 的父级,其中“父级”的定义与 Excel 的父级定义无关。我进一步猜测您不知道如何通过数字访问控件。

下面的宏通过其在集合 Controls 中的索引号列出了窗体上每个控件的名称、类型和顶部位置。任何 属性 控件都可以通过这种方式访问​​。如果控件 Xxxxx 是控件 Yyyyy 的父控件,您可以在加载表单时扫描集合以查找它们的索引号,并记录此信息以备需要时使用。

Private Sub UserForm_Initialize()

  Dim InxCtrl As Long
  Dim LenNameMax As Long
  Dim LenTypeMax As Long

  LenNameMax = 0
  For InxCtrl = 0 To Controls.Count - 1
    If LenNameMax < Len(Controls(InxCtrl).Name) Then
      LenNameMax = Len(Controls(InxCtrl).Name)
    End If
    If LenTypeMax < Len(TypeName(Controls(InxCtrl))) Then
      LenTypeMax = Len(TypeName(Controls(InxCtrl)))
    End If
  Next

  Debug.Print PadR("Name", LenNameMax) & "|" & PadR("Type", LenTypeMax) & "|     Top"
  For InxCtrl = 0 To Controls.Count - 1
    Debug.Print PadR(Controls(InxCtrl).Name, LenNameMax) & "|" & _
                PadR(TypeName(Controls(InxCtrl)), LenTypeMax) & "|" & _
                PadL(Format(Controls(InxCtrl).Top, "#,###.00"), 8)
  Next

End Sub

这是我创建新控件并设置一些值的函数。最后一个任务是我想设置父级的地方 Public 函数 apply_change(ihm_f, oNode, iMyName$, project$)

Dim new_elem
Dim oSubNodes As IXMLDOMNode

If oNode.Attributes.getNamedItem("Type").Text <> "Page" Then
    If (oNode.Attributes.getNamedItem("Type").Text = "RefEdit") Then

        Set new_elem = ihm_f.Designer.Controls.Add("RefEdit.Ctrl", oNode.nodeName, True)

    Else
        Set new_elem = ihm_f.Designer.Controls.Add("Forms." & oNode.Attributes.getNamedItem("Type").Text & ".1", oNode.nodeName, True)
    End If
    With new_elem
        On Error Resume Next
        .Width = oNode.Attributes.getNamedItem("Width").Text
        .Top = oNode.Attributes.getNamedItem("Top").Text
        .Left = oNode.Attributes.getNamedItem("Left").Text
        .Height = oNode.Attributes.getNamedItem("Height").Text
        Set .Parent = get_parent(oNode.ParentNode.nodeName, oNode, ihm_f)
    End With
    If oNode.Attributes.getNamedItem("Type").Text = "MultiPage" Then
    Call new_elem.Pages.Remove(0)
    Call new_elem.Pages.Remove(0)
     For Each oSubNodes In oNode.ChildNodes()
        Call new_elem.Pages.Add(oSubNodes.BaseName, oSubNodes.Attributes.getNamedItem("Caption").Text, oSubNodes.Attributes.getNamedItem("Index").Text)
     Next oSubNodes
    End If
End If
Set apply_change = ihm_f
End Function

getparent 函数 return 一个控件,它可以是任何东西..比如文本框或组合框等..