【问题标题】:Is there a way to list all the textboxs, comboboxs, labels from a form that has multipages in a sheet?有没有办法列出表单中包含多页的表单中的所有文本框、组合框和标签?
【发布时间】:2021-03-05 00:31:22
【问题描述】:

您好 Stackoverflow 社区,我想知道是否有一种方法可以从多页表单中列出所有控件(标签、文本框、组合框)?这是因为我需要更新脚本,但它有大约 30 页和大约 200 个控件。

【问题讨论】:

    标签: excel vba forms controls


    【解决方案1】:

    将此代码粘贴到表单的代码表并将其链接到您可能为此临时添加的按钮。

    Private Sub GetControlNames()
        
        Dim Ctl As Object
        
        For Each Ctl In Me.Controls
            Debug.Print Ctl.Name, Ctl.Parent.Name
        Next Ctl
    End Sub
    

    单击按钮后,所有控件名称都将列在立即窗格中。在我的测试中,Parent.Name 是表单的名称,但我希望它会在您的设置中显示控件所在的页面。然后,您可以将 Me.Controls 替换为 Me.Controls([Page Name]).Controls 并获取项目任何页面上的控件名称。这个想法可能需要稍微调整一下,因为我没有尝试过。

    【讨论】:

      【解决方案2】:

      Pages 似乎没问题 我将它放入一个模块中,然后从您调用它的表单中的任何位置

      ListAllMyControls Me, ""
      

      为我工作 - 我认为 - 我的表单也有很多页面和很多控件 - 我没有进行彻底的检查,但这列出了具有多级层次结构的对象,例如

      Userform1.MultiPage1.Page1.Label1
      Userform1.MultiPage1.Page1.TextBox1
      Userform1.MultiPage1.Page2.Label1
      Userform1.MultiPage1.Page2.TextBox1
      

      下面是主程序

      Public Sub ListAllMyControls(SrcObj As Object, dParentNames As String)
         Dim dCtr As Long, xObj As Object, ParentsWere As String, ParentsB4 As String
         
         ' List this Control
         ParentsWere = dParentNames
         dParentNames = IIf(dParentNames = "", "", dParentNames & ".") & SrcObj.Name
         Debug.Print dParentNames
         
         dCtr = 0
         On Error Resume Next
         dCtr = SrcObj.Controls.Count
         On Error GoTo 0
         
         If UCase(Left(SrcObj.Name, 9)) = "MULTIPAGE" Then
            For Each xObj In SrcObj.Pages
               ParentsB4 = dParentNames
               ListAllMyControls xObj, dParentNames
               dParentNames = ParentsB4
            Next xObj
         Else
            If dCtr > 0 Then
               ' List all my controls
               For Each xObj In SrcObj.Controls
                  ParentsB4 = dParentNames
                  ListAllMyControls xObj, dParentNames
                  dParentNames = ParentsB4
               Next xObj
            Else
               dParentNames = ParentsWere
            End If
         End If  ' MultiPage
      End Sub
      

      添加评论 - 问题是这似乎在页面中列出了两次对象。它将它们列为页面的控件以及页面最终所在表单的控件。

      【讨论】:

      • 我尝试将 Public Sub ListAllMyControls 放在一个模块中,并将 ListAllMyControls Me, "" 放在表单中的脚本中。但出现以下错误:“Run-tiem error '1004' Application-defined or object .defined error. :(
      • @Andres 它在哪一行崩溃,你运行的是什么版本的 Excel?我只是从我的答案中复制了代码并将其粘贴到具有不同形式的不同工作簿中,并且运行良好
      • Burn 我有这个版本:(Microsoft Excel 365 (2016) 32-bit),错误是运行时错误,没有显示任何要解决的行
      • 你锁定VBA项目了吗?如果是这样解锁它
      • 我是所有者,我没有 VBA 项目的任何密码。在运行宏之前我是否必须对代码进行任何更改?
      猜你喜欢
      • 2020-02-22
      • 2011-06-08
      • 2023-02-25
      • 2013-12-14
      • 1970-01-01
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      • 2018-05-03
      相关资源
      最近更新 更多