如何循环使用具有可变对象名称的userform框架

时间:2017-01-24 19:00:09

标签: vba excel-vba userform excel

我正在尝试在我的VBA Multipage中的每个User_Form页面中循环一组特定的帧。但是,似乎我不能像每个帧控件一样使用变量对象名称。

我收到错误

  

对象不支持此属性或方法

在以下一行

For Each cCont in Me.MultiPage1.Pages(PageName).Frames(DataFrame).Controls

我的代码

Do While x <= Me.MultiPage1.Pages.Count
    PageName = "Page" & CStr(x)
    DataFrame = "DataFrame" & CStr(x)
    For Each cCont In Me.MultiPage1.Pages(PageName).Frames(DataFrame).Controls

2 个答案:

答案 0 :(得分:1)

你实际上无法按照自己的想法进行迭代。

首先,您需要遍历MultiPage1的所有页面。

其次,遍历当前Controls内的所有Page,并检查它们是否为Frame类型,如果它们是你可以在Frame内迭代但是语法略有不同(参见下面的代码)。

<强>代码

Option Explicit

Private Sub IterateIn_MultiPage()

Dim x As Long, j As Long
Dim cCont As Control

For x = 0 To Me.MultiPage1.Pages.Count - 1 ' <-- loop through all MultiPage Pages

    For Each cCont In Me.MultiPage1.Pages(x).Controls ' <-- loop through controls of current page
        If TypeOf cCont Is Frame Then ' <-- check if control type is Frame
            For j = 0 To cCont.Controls.Count - 1   '<-- loop through all items related to the current Frame collection
                MsgBox cCont.Controls(j).Name '<-- display a message box
            Next j
        End If
    Next cCont

Next x

End Sub

答案 1 :(得分:0)

感谢您帮助整理代码@Shai,让其他人想知道最终代码在这里是什么样子。这将循环遍历每个多页中的每个帧,并在所需范围内粘贴已选中复选框的标题。

Option Explicit

Sub IterateIn_MultiPage()
Dim x As Long, j As Long
Dim cCont As Control
Dim counter As Integer
Dim y As Integer
Dim Range As String
y = 1

For x = 0 To ImportData.MultiPage1.Pages.Count - 1
counter = 0
    For Each cCont In ImportData.MultiPage1.Pages(x).Controls
        Do While counter < 1
            If TypeOf cCont Is Frame Then
                For j = 0 To cCont.Controls.Count - 1
                    If cCont.Controls(j).Value = True Then
                            Range = "E" & y
                            If counter = 0 Then
                                Worksheets("Calculations").Range(Range) = cCont.Controls(j).Caption
                                counter = counter + 1
                            ElseIf counter = 1 Then
                                Worksheets("Calculations").Range(Range) = Worksheets("Calculations").Range(Range) & " & " & cCont.Controls(j).Caption
                                y = y + 1
                            End If
                    End If
                Next j
            End If
        Loop
    Next cCont

Next x

End Sub