使用Access VBA中的代码自动生成文本框

时间:2016-06-27 13:54:19

标签: vba ms-access access-vba

我尝试使用Auto Subs,但我无法理解......

我有多个(在这种情况下为59)表单中的文本框/按钮,所有内容都带有单击事件。但是在VBA中我不希望每个代码都使用代码,因为我想让Form易于控制并将其用于不编码的人,并且 59 Click Subs 将是非常难看,如果我想添加更多,我需要在VBA代码中创建另一个Sub。

真正的问题是:是否有某种方法可以为每个具有不同变量的文本/按钮执行自动代码(Sub)?

E.G:

Text1_Click + Code -> Variable: 1
Text2_Click + Code -> Variable: 2
Text3_Click + Code -> Variable: 3   --> Text(?)_Click + Code -> Variable: ?
Text4_Click + Code -> Variable: 4
Text5_Click + Code -> Variable: 5

3 个答案:

答案 0 :(得分:2)

创建VBA功能并将其用于每个文本框点击属性:railscast

在您的示例中,文本框的名称为=MyFunction()Text1,您似乎希望Text5包含文本框名称中的数字。使用Variable提取该号码很容易。

Mid()

如果要将该方法扩展到带编号的命令按钮,请包含此...

Public Function MyFunction()
    Dim strControl As String
    Dim Variable As Variant

    strControl = Application.Screen.ActiveControl.Name
    Variable = Null
    If strControl Like "Text*" Then
        Variable = Val(Mid(strControl, 5))
    End If
    Debug.Print strControl & "_Click -> Variable: " & Nz(Variable, "Null")
End Function

如果您需要以编程方式分配 On Click 属性,请循环控制并设置每个 If strControl Like "Command*" Then Variable = Val(Mid(strControl, 8)) End If

答案 1 :(得分:1)

在您的表单中有按钮和以下代码

Option Explicit

Public colCustomControls As Collection

Private Sub Form_Open(Cancel As Integer)

Dim ctl As Control
Dim clsCustom As clsCustomButton

    Set colCustomControls = New Collection

    For Each ctl In Me.Controls
        Set clsCustom = New clsCustomButton
        clsCustom.INITIALISE ctl
        colCustomControls.Add clsCustom
    Next ctl

End Sub

然后是一个名为clsCustomButton

的类
Option Explicit

Private WithEvents cbCustom As CommandButton

Public Sub INITIALISE(cb As CommandButton)
    Set cbCustom = cb
    cb.OnClick = "[Event Procedure]"
End Sub

Private Sub cbCustom_Click()
    Select Case cbCustom.Name
        Case "Command0": MsgBox "Button1 clicked"
        Case "Command1": MsgBox "Button2 clicked"
    End Select
End Sub

正在发生的事情是集合模仿,me.Controls集合在表单中,但我们正在使所有按钮成为类,因此,使用类_click事件。您可以修改初始化以获取proc名称事件,对于子调用,然后使用application.Run来调用代码。

喜欢这样

Option Explicit

Private WithEvents cbCustom As CommandButton
Private strProcCall As String

Public Sub INITIALISE(cb As CommandButton, strProc As String)
    Set cbCustom = cb
    strProcCall = strProc
    cb.OnClick = "[Event Procedure]"
End Sub

Private Sub cbCustom_Click()
    Application.Run strProcCall
End Sub

Option Explicit

Public colCustomControls As Collection

Private Sub Form_Open(Cancel As Integer)

Dim ctl As Control
Dim clsCustom As clsCustomButton

    Set colCustomControls = New Collection

        Set clsCustom = New clsCustomButton
        clsCustom.INITIALISE Me.Controls("Command0"), "MACRO_1"
        colCustomControls.Add clsCustom

        Set clsCustom = New clsCustomButton
        clsCustom.INITIALISE Me.Controls("Command1"), "MACRO_2"
        colCustomControls.Add clsCustom

End Sub

答案 2 :(得分:0)

是的,您可以通过以下方式引用控件:

n = 5
Set ctl = Me("Text" & CStr(n))

然后 ctl 将引用 Me!Text5

但请查看 WithEvents How to write generic code ...