且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在运行时创建控件Access VB?

更新时间:2023-12-06 15:06:22

您需要的文档在这里(这些专门针对 Access VBA):

The documentation you need is here (these are specifically for Access VBA):

根据文档,此功能有一些很大的限制:

According to the documentatin, there are some big limitations to this feature:

  • 在表单的生命周期内限制为 754 个控件(这不会通过删除它们来重置,因此您可能很快就会遇到此限制)
  • 必须在设计视图中完成(所以不能在 mde/accde 中完成)
  • 它在多用户环境中的表现值得怀疑.

由于这些限制,不建议这样做,除非您最初是用来设计表单的.

Because of these limitations, it is inadvisable, unless you are using to design forms initially.

重复问题:你怎么动态在 MS Access 表单上创建控件?

响应 OP 的建议,这是我的测试代码,它能够添加 40 个控件并重复该过程 50 次而不会超过 754 的限制(我在测试中重复使用了 40 个名称).

In response to the OP's suggestion, here is my test code which was able to add 40 controls and repeat the process 50 times without exceeding the 754 limit (I reused 40 names in my test).

警告 1 这是不可取的,因为它只能在设计视图中完成,而不能在 mde/accde 中工作.

Caveat 1 This is inadvisable because it can only be done in design view which will not work in an mde/accde.

警告 2:它在多用户环境中的表现值得怀疑.

Caveat 2: It is questionable how it will perform in a multi-user environment.

此代码来自具有两个按钮的表单.它打开一个名为Form2"的第二个表单

This code is from a form with two buttons. It opens a second form named "Form2"

Option Compare Database
Option Explicit

Private Const FORM_NAME As String = "Form2"
Private m_nCounter As Long

Private Sub cmdCreate_Click()
    runDynamicForm
End Sub

Private Sub cmdRepeat_Click()

    Dim n As Long

    m_nCounter = 0

    For n = 0 To 50
        runDynamicForm
        DoEvents
        DoCmd.Close acForm, FORM_NAME, acSaveNo
        DoEvents
    Next 'n

    MsgBox m_nCounter

End Sub

Private Sub runDynamicForm()

    Const DYNAMIC_TAG As String = "dynamic"

    Dim n As Long
    Dim frm As Form
    Dim ctl As Access.Control

    On Error GoTo EH

    Application.Echo False

    DoCmd.OpenForm FORM_NAME, acDesign
    Set frm = Application.Forms(FORM_NAME)

    For n = frm.Controls.Count - 1 To 0 Step -1
        Set ctl = frm.Controls(n)
        If ctl.Tag = DYNAMIC_TAG Then
            Application.DeleteControl FORM_NAME, ctl.Name
        End If
    Next 'n

    For n = 1 To 20

        With Application.CreateControl(FORM_NAME, acLabel, acDetail, , , 400, n * 300, 1500, 300)

            .Name = "lbl" & n
            .Caption = "Question " & n
            .Visible = True
            .Tag = DYNAMIC_TAG

        End With

        With Application.CreateControl(FORM_NAME, acTextBox, acDetail, , , 2000, n * 300, 3000, 300)

            .Name = "txt" & n
            .Visible = True
            .TabIndex = n - 1
            .Tag = DYNAMIC_TAG

        End With

        m_nCounter = m_nCounter + 2

    Next 'n

    DoCmd.Close acForm, FORM_NAME, acSaveYes

    DoCmd.OpenForm FORM_NAME, acNormal

    GoTo FINISH

EH:
    With Err
        MsgBox "Error:" & vbTab & .Number & vbCrLf _
            & "Source" & vbTab & .Source & vbCrLf _
            & .Description
    End With

FINISH:

    Application.Echo True

End Sub