我正在撰写一个简单的多条件搜索表单。 为第一个切换按钮设置的Access VBA功能如下所示:
Private Sub ToggleQ1_Click()
Select Case ToggleQ1.Value
Case True
CondQ1 = "AND"
ToggleQ1.Caption = CondQ1
Case False
CondQ1 = "OR"
ToggleQ1.Caption = CondQ1
End Select
End Sub
ToggleQ1 =按钮的名称
CondQ1 =与字符串一起使用的变量,用于创建条件搜索。
创建50多个相同的按钮代码可能是荒谬的,仅在名称上有所区别(例如" ToggleQ50"以及" CondQ50")
有没有办法让它模块化和可重复使用? 非常感谢你提前。
答案 0 :(得分:3)
在表单模块中创建一个函数(不是sub),如下所示:
Private Function SetCaption()
Dim clickedButton As Control
Dim CondQ1 As String
Set clickedButton = Me.ActiveControl
Select Case clickedButton.Value
Case True
CondQ1 = "AND"
clickedButton.Caption = CondQ1
Case False
CondQ1 = "OR"
clickedButton.Caption = CondQ1
End Select
End Function
在表单设计器中选择所有50个按钮,然后键入属性On Click
=SetCaption()
因此,您不需要为每个按钮创建事件处理程序。
答案 1 :(得分:2)
创建另一个子并将单击的按钮发送给它。与此类似:
Private Sub cmdTest01_Click()
SetCaption cmdTest01
End Sub
Private Sub cmdTest02_Click()
SetCaption cmdTest02
End Sub
Private Sub SetCaption(clickedButton As CommandButton)
Dim CondQ1 As String
Select Case clickedButton.Caption
Case "Test01"
CondQ1 = "AND"
clickedButton.Caption = CondQ1
Case "Test02"
CondQ1 = "OR"
clickedButton.Caption = CondQ1
End Select
End Sub
案例块可以简化为
Case "Test01"
clickedButton.Caption = "AND"
Case "Test02"
clickedButton.Caption = "OR"
答案 2 :(得分:0)
使用 WithEvents 。在加载和卸载表单时需要一些代码,但每个按钮的代码为零。
可以在此处找到您应该能够适应的完整代码的类似示例:
Create Windows Phone Colour Palette and Selector using WithEvents
和 GitHub : VBA.ModernTheme
代码段:
Private ControlCollection As Collection
Private Sub Form_Load()
' Load events for all colour value textboxes.
Dim EventProcedure As ClassTextboxSelect
Dim Control As Access.Control
Set ControlCollection = New Collection
For Each Control In Me.Controls
If Control.ControlType = acTextBox Then
Set EventProcedure = New ClassTextboxSelect
EventProcedure.Initialize Control
ControlCollection.Add EventProcedure, Control.Name
End If
Next
Set EventProcedure = Nothing
Set Control = Nothing
End Sub
Private Sub Form_Open(Cancel As Integer)
Dim Index As Integer
' Set colour palette.
For Index = 0 To 20
Me("Box" & CStr(Index + 1)).BackColor = PaletteColor(Index)
Me("Name" & CStr(Index + 1)).Value = LiteralWpThemeColor(PaletteColor(Index))
Me("Css" & CStr(Index + 1)).Value = RGBHex(PaletteColor(Index))
Me("Vba" & CStr(Index + 1)).Value = PaletteColor(Index)
Me("Hex" & CStr(Index + 1)).Value = "&H" & Hex(PaletteColor(Index))
Next
End Sub
Private Sub Form_Unload(Cancel As Integer)
' Unload events for all colour value textboxes.
Dim EventProcedure As ClassTextboxSelect
For Each EventProcedure In ControlCollection
EventProcedure.Terminate
Next
Set EventProcedure = Nothing
Set ControlCollection = Nothing
End Sub