gpt4 book ai didi

vba - Access 2016 VBA - 创建自定义控件集合,手动指定控件名称

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:16:05 25 4
gpt4 key购买 nike

由于 Access 中没有垂直控制选项卡,我正在创建一个假的。
我写了这段代码来突出显示(将前景色更改为白色)当前页面:

Private Sub updateBtnColor()
Dim currentPageIndexSZero As Long
Dim ctl As Control
currentPageIndexSZero = Me.tab1
For Each ctl In Me.Controls
If ctl.Tag = "page" & CStr(currentPageIndexSZero) Then
ctl.ForeColor = white
ElseIf InStr(1, ctl.Tag, "page", vbBinaryCompare) Then
ctl.ForeColor = black
End If
Next ctl
End Sub

每个按钮都有它引用的页面标签,形式如下:

page0
page1
...
pageN

所以循环基本上检查当前页面,找到带有适当标签的按钮(假设我正确命名它们)并突出显示其文本。

现在这可能会很慢,因为我有一个繁重的表单或错误的做法,所以我想创建一个自定义集合而不是遍历整个控件集合。
我想创建这样的结构,这样我就可以遍历它,比如:

Enum myButtons
button1 = Forms!myForm!button1
button2 = Forms!myForm!button2
button3 = Forms!myForm!button3
button4 = Forms!myForm!button4
End Enum

然后:

Public Sub updateBtnColor()
Dim curPageZ as Long
Dim button as Control
For Each button in myButtons
With button
If Right$(CStr(.Name, 1)) = curPageZ
.ForeColor = 16777215 ' White
Else ' No need for an additional ElseIf since I already know these are only the wanted buttons
.ForeColor = 0 ' Black
End If
End With
Next button
End Sub

创建这种结构的最优雅/最快/最好/正确的方法是什么,或者,如果我的想法不是那么好,创建这种逻辑的方法是什么?
谢谢!

最佳答案

通过控件循环工作非常快,但如果您想加快速度,请使用 Collection 来存储对象,而不是 Enum。也可以使用 For Each... 循环收集。

在表单模块级别为您的按钮创建一个集合:

Dim mcolMyButtons As New Collection

然后在 Open 或 Load 事件中填充此集合。您可以使用标签:

Dim ctl As Control
For Each ctl In Me.Controls
If TypeOf ctl Is CommandButton Then
If ctl.Tag Like "page*" Then
mcolMyButtons.Add ctl
End If
End If
Next

或者直接添加你想要的按钮:

mcolMyButtons.Add Me.Button1
mcolMyButtons.Add Me.Button2
mcolMyButtons.Add Me.Button3
mcolMyButtons.Add Me.Button4

然后你的潜艇:

Private Sub updateBtnColor()
Dim ctl As Control
For Each ctl In mcolMyButtons
If ctl.Tag = "page" & Me.tab1 Then
ctl.ForeColor = vbWhite
Else
ctl.ForeColor = vbBlack
End If
Next ctl
End Sub

关于vba - Access 2016 VBA - 创建自定义控件集合,手动指定控件名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40835167/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com