vba - 循环遍历用户窗体上的控件以隐藏特定控件
问题描述
我浏览了很多关于此的帖子并提出了以下解决方案,但我想知道是否有更有效的编码方式。
这些案例基于用户选择的组合框值 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
解决方案
未经测试:
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
永远不会通过
推荐阅读
- php - 如何在 laravel 8 中使用 json web token (jwt) 进行多重身份验证?
- google-cloud-platform - Google Cloud Vision API 对象检测模型在 Raspberry Pi 上出现总线错误
- gtsummary - 将 tbl_summary 中的频率和百分比拆分为两个单独的列
- python - 合并后python pandas更改顺序和列名
- apache-flink - Apache Flink 在 UI 中显示自定义指标,但普罗米修斯指标报告器没有抓取它们
- laravel - Laravel:如何保存到两个表中,但是,第一个表的 id 将作为外部 id 保存到第二个表中
- c++ - 子聚合的指定初始化器是否需要花括号?
- clickhouse - 获取 ClickHouse 表前 n 行的校验和(cityHash64)
- blazor - 有什么方法可以禁止组件使用“ShouldRender”进行渲染,但允许其子组件在他们认为合适的时候重新渲染?
- r - 用 R 对 A 行的 A 元素和 A 矩阵的 A 列进行排序