使用VBA将VBA代码添加到MS Access用户表单

时间:2017-06-15 08:28:27

标签: vba ms-access ms-access-2007

我有一个自动生成表单的脚本。此表单只是临时的,可以在关闭后删除。为了防止必须手动执行,我想添加一个按钮或form_close()方法,其中应该有一些代码来删除表单(如果可以的话)。

否则,我希望能够防止弹出窗口强制我保存表单并在关闭后给它起一个名字(如下图荷兰语所示)。

'save form' pop-up (in Dutch)

我无法禁用此弹出窗口,也无法使用VBA代码添加VBA代码。任何人都可以告诉我这可能吗?也许举个例子?

2 个答案:

答案 0 :(得分:1)

表单中不需要VBA代码来执行此操作,只需从按钮的OnClick事件中调用公共函数。

' This is called from the "Close" button on the temp form
Public Function CloseWithoutSave(fName As String)
    DoCmd.Close acForm, fName, acSaveNo
End Function

' Demo
Public Sub CreateTestForm()

    Dim F As Form
    Dim btn As CommandButton

    Set F = Application.CreateForm()
    F.Caption = "This is a test form!"

    Set btn = CreateControl(F.Name, acCommandButton, Left:=100, Top:=100)
    btn.Caption = "Close me"
    btn.OnClick = "=CloseWithoutSave(""" & F.Name & """)"

    ' Open test form in form view
    DoCmd.Restore
    DoCmd.OpenForm F.Name, acNormal

End Sub

答案 1 :(得分:0)

You can't add modules to forms without saving them, as far as I know, and forms need to be in design view to have a module added to them (just like when you add them through the GUI).

To start from your starting point (you have an open unsaved form):

Public Sub AddModuleToOpenUnsavedForm(strModuleText As String)
    'Save the form name to a variable
    Dim strFormName As String
    strFormName = Screen.ActiveForm.Name
    'Save and close the form
    DoCmd.Save acForm, strFormName
    DoCmd.Close acForm, strFormName, acSaveYes
    'Open the form back up in desing view
    DoCmd.OpenForm strFormName, acDesign
    'Add a module to it
    Forms(strFormName).HasModule = True
    'Add code to the module
    Forms(strFormName).module.InsertText strModuleText
    'Close it again
    DoCmd.Save acForm, strFormName
    DoCmd.Close acForm, strFormName, acSaveYes
    'Open the form back up again
    DoCmd.OpenForm strFormName, acNormal
End Sub

Note that this does prompt a database-wide save. If you have any unsaved open objects, you will be prompted to save them.

Obviously, you can delete the form after using it, but you will have to do it actively instead of leaving it unsaved.