循环浏览组框中的每个控件

时间:2018-10-22 21:35:32

标签: excel vba excel-vba

我在excel工作表中有一个对象列表,每个对象都有一个复选框和代表该对象的组框内的4个下拉列表。

我可以使用VBA遍历工作表中的每个组框,但是如何遍历组框中的每个控件?

Dim oGroupBox As GroupBox
Dim cntrl As Control
For Each oGroupBox In Worksheets("Grapher").GroupBoxes
    For Each cntrl In oGroupBox.Controls
        Debug.Print (cntrl.Name)
    Next cntrl
Next oGroupBox

1 个答案:

答案 0 :(得分:0)

下面假定您没有将FormControl形状分组。它将列出TopLeftCell位于GroupBox范围内的所有FormControl名称(从 TopLeftCell BottomRightCell )。

您可以添加新的Sub代码,以针对所使用的每种形式的控件采取不同的操作。

Option Explicit

Sub ListControlsInGroupBoxes()
    Dim oGroupBox As GroupBox
    For Each oGroupBox In ThisWorkbook.ActiveSheet.GroupBoxes
        ListObjectsInGroupBox oGroupBox
    Next oGroupBox
End Sub

Private Sub ListObjectsInGroupBox(GBox As GroupBox)
    Dim oBoxRange As Range, oShp As Shape
    Set oBoxRange = Range(GBox.TopLeftCell, GBox.BottomRightCell)
    Debug.Print String(50, "-")
    Debug.Print "Group Box """ & GBox.Name & """ has range " & oBoxRange.Address
    For Each oShp In GBox.Parent.Shapes
        ' Deal only with FormControls
        If oShp.Type = msoFormControl Then
            ' Display FormControl's name if inside the GroupBox range
            If Not Intersect(oShp.TopLeftCell, oBoxRange) Is Nothing Then
                ' Obmit itself
                If Not oShp Is GBox Then
                    Debug.Print """" & oShp.Name & """"
                End If
            End If
        End If
    Next oShp
    Set oBoxRange = Nothing
End Sub