如何编写泛型代码,通过实例化与窗体关联的底层类来打开窗体



我认为这将被归类为高级访问问题。

我试图通过实例化与表单相关的底层类来编写通用代码来打开表单。我不知道在传递"表单类"作为参数时使用哪种类型。

我认为下面的"模拟示例"代码更好地解释了我的问题:

Option Compare Database
Option Explicit
Sub OpenAllMyForms()
    ' I have three access forms named MyFormName1, MyFormName2 and MyFormName3
    ' Say I use this code to open all three of them
    Form_Open_MyFormName1
    ' Form_Open_MyFormName2     ' In this example I have not included the procedure used to open MyFormName2 and MyFormName3
    ' Form_Open_MyFormName3
End Sub
Function Form_Open_MyFormName1() As Form
    '
    ' Current Code  (Each form that gets opened has a function like this)
    '
    Dim frm As Form
    Set frm = New Form_MyFormName1
    ' Note that the Form_ is very significant.
    ' The form name in the access navigation pane is shown as "MyFormName1"
    ' preceeding this name with "Form_" causes the underlying class to be returned
    ' which is implements the access "Form" class.  (I think this is how you say it in OO speak)

    ' I then add this form to a collection, but lets not complicate the example
    ' clnOfForms_MyFormName1.add Item:=frm, Key:=CStr(frm.Hwnd)
    Set Form_Open_MyFormName1 = frm
    frm.Visible = True
    Set frm = Nothing
End Function

Sub OpenAllMyFormsNEW()
    '
    ' I want to write a generic function that will open any form
    ' so I replace the sub OpenAllMyForms (ie above) with this sub.
    ' I no longer have a "Form_Open_MyFormName1" function for each form
    ' but instead use Form_Open - see below.
    Dim Frm1 As Form
    Dim Frm2 As Form
    Dim Frm3 As Form
    '
    ' Note that the Form_ is very significant.
    ' The form name in the access navigation pane is shown as "MyFormName1"
    ' preceeding this name with "Form_" causes the underlying class to be returned
    '
    Set Frm1 = Form_Open(aForm:=Form_MyFormName1)
    Set Frm2 = Form_Open(aForm:=Form_MyFormName2)
    Set Frm3 = Form_Open(aForm:=Form_MyFormName3)
End Sub
Function Form_Open(aFormClass As WhatTypeShouldIuseHere) As Form
    '
    ' Here is the new function, however I don't know how to get it to work.
    ' I don't know what type to use for the parameter aFormClass see "WhatTypeShouldIuseHere" above.
    '
    Dim frm As Form
    Set frm = New aFormClass
    Set Form_Open = frm
    Set frm = Nothing
End Function

表单就是类本身。

但是不要在这上面花太多时间。Access使用对象和类,但不是面向对象的。如果你追求花哨的编程,VBA不适合你。

你可以使用WithEvents达到某个点。关于这个主题的文档很少,但是这个博客应该可以让您入门:

浏览到A Little History

问题是,当您将这种技术推进得太远时,Access就会崩溃。不要指望这个会被纠正;微软不把Access看作一个开发者环境,而是一个超级用户和SharePoint的工具。

所以寻找Visual Studio,它会尊重你的努力,而不是浪费你的时间。

最新更新