首页 > 解决方案 > 循环遍历用户窗体上的控件以隐藏特定控件

问题描述

我浏览了很多关于此的帖子并提出了以下解决方案,但我想知道是否有更有效的编码方式。

这些案例基于用户选择的组合框值 0 到 8,然后标签和文本框将根据组合框中的数字显示。

我想隐藏或显示的所有标签和文本框都以“b”开头,然后是数字 1 到 8,如下面的代码所示。我感谢任何提高我正在运行的循环效率的建议。

 Select Case LendStart.lsNumBorr.Value
    Case Is = 0
        For Each ctrl In LendStart.Controls
            If Left(ctrl.Name, 1) = "b" Then
                ctrl.Visible = False
            End If
        Next
    Case Is = 1
        For Each ctrl In LendStart.Controls
            If Left(ctrl.Name, 2) = "b1" Then
                ctrl.Visible = True
                    If Left(ctrl.Name, 2) = "b2" Or Left(ctrl.Name, 2) = "b3" Or Left(ctrl.Name, 2) = "b4" Or Left(ctrl.Name, 2) = "b5" Or Left(ctrl.Name, 2) = "b6" Or Left(ctrl.Name, 2) = "b7" Or Left(ctrl.Name, 2) = "b8" Then
                        ctrl.Visible = False
                    End If
            End If
        Next
    Case Is = 2
        For Each ctrl In LendStart.Controls
            If Left(ctrl.Name, 2) = "b1" Or Left(ctrl.Name, 2) = "b2" Then
                ctrl.Visible = True
                    If Left(ctrl.Name, 2) = "b3" Or Left(ctrl.Name, 2) = "b4" Or Left(ctrl.Name, 2) = "b5" Or Left(ctrl.Name, 2) = "b6" Or Left(ctrl.Name, 2) = "b7" Or Left(ctrl.Name, 2) = "b8" Then
                        ctrl.Visible = False
                    End If
            End If
        Next
 End Select

标签: vbaexcel-2013

解决方案


未经测试:

Sub Tester()

    Dim i As Long, numBorr, firstTwo

    numBorr = LendStart.lsNumBorr.Value

    For Each ctrl In LendStart.Controls
        If Left(ctrl.Name, 1) = "b" Then

            firstTwo = Left(ctrl.Name, 2)

            For i = 1 To 8
                If firstTwo = "b" & i Then
                    ctrl.Visible = (i <= numBorr)
                End If
            Next i

        End If
    Next

End Sub

请注意,您发布的代码中存在逻辑错误:

If Left(ctrl.Name, 2) = "b1" Then
    ctrl.Visible = True
    If Left(ctrl.Name, 2) = "b2" Or Left(ctrl.Name, 2) = "b3" Or _
       Left(ctrl.Name, 2) = "b4" Or Left(ctrl.Name, 2) = "b5" Or _
       Left(ctrl.Name, 2) = "b6" Or Left(ctrl.Name, 2) = "b7" Or _
       Left(ctrl.Name, 2) = "b8" Then

                    ctrl.Visible = False
    End If
End If

外部If检查“b1”,但在这种情况下,内部If永远不会通过


推荐阅读