从DoCmd.RunSQL中的组合框访问调用全局变量

时间:2014-12-17 21:28:38

标签: database vba ms-access combobox global-variables

请帮助我学习VBA的最新尝试。我在Access 2007中构建数据库。

当数据库启动时,有一个带有组合框的表单,人们可以在其中选择他们的名字,然后点击按钮。我创建了一个名为Globals的模块来将组合框选项存储为变量。这是代码,请告诉我它是否错了!

Public Function GetAssocName() As String
        AssocName = Forms!frm_ChooseAssoc!ChooseAssocComboBox.Value
End Function

我的理解是,只要数据库处于打开状态,无论窗体是打开还是关闭,这都会将选项存储为的变量。无论如何,我选择做Me.Visible = FALSE而不是关闭表格。

然后,我有一个sub,它将一些东西附加到数据库中的两个表中。这是我的代码,请告诉我它是错还是坏!

Public Sub Add2TablesButton_Click()
    '
    Dim AreYouSuremsgbox As String
    '
    AreYouSuremsgbox = MsgBox("Are you sure you want to do this?", vbExclamation + vbYesNo, "Are you sure?")
    '
    If (AreYouSuremsgbox = vbYes) Then
        DoCmd.Hourglass True
        DoCmd.SetWarnings False
        DoCmd.RunSQL "INSERT INTO tbl_OrderArchive ([Loan#], OrderDate, Rush, Associate) " & _
                     "SELECT qry_Orders.[Loan #], Date(), qry_Orders.Rush, AssocName " & _
                     "FROM qry_Orders WHERE qry_Orders.[Order Placed in OrderApp]=TRUE;"

        DoCmd.RunSQL "INSERT INTO tbl_CE ([Loan#], [InvLoan#], InvCode, BorrowerName, Status, Rush) " & _
                     "SELECT qry_Orders.[Loan #], qry_Orders.[Inv #], qry_Orders.[Inv Code], " & _
                     "qry_Orders.Borrower, qry_Orders.Status, qry_Orders.Rush " & _
                     "FROM qry_Orders WHERE qry_Orders.[Order Placed in OrderApp]=TRUE;"
        DoCmd.SetWarnings True
        DoCmd.Hourglass False
        MsgBox "Done!", vbOKOnly, "Done!"
    ElseIf (AreYouSuremsgbox = vbNo) Then
        Exit Sub
    End If
End Sub

请注意第一个DoCmd.RunSQL,它说的是AssocName。我希望它调用全局变量并将其附加到表中。但每次我测试这个东西时,它都要求我在物理上输入AssocName。

我已经尝试了很多语法,一整天用Google搜索,我做错了什么?

非常感谢你的时间。

1 个答案:

答案 0 :(得分:1)

在代码窗口中,单击“插入”模块'和过去的内容如下:

Option Compare Database
Option Explicit

Global AssocName  As String

Public Function GetAssocName() As String
    GetAssocName = AssocName  
End Function

然后在用户选择名称后,使用用户名组合框的形式。

AssocName = Me.ChooseAssocComboBox 

然后从以下位置更改以下行:

DoCmd.RunSQL "INSERT INTO tbl_OrderArchive ( [Loan#], OrderDate, Rush, Associate ) " & _
     "SELECT qry_Orders.[Loan #], Date(), qry_Orders.Rush, AssocName FROM qry_Orders 
     "WHERE qry_Orders.[Order Placed in OrderApp]=TRUE;"

要:(假设您想要当前用户名?)

    DoCmd.RunSQL "INSERT INTO tbl_OrderArchive ( [Loan#], OrderDate, Rush, Associate ) " & _
     "SELECT qry_Orders.[Loan #], Date(), qry_Orders.Rush, '" & GetAssocName & "' FROM qry_Orders 
     "WHERE qry_Orders.[Order Placed in OrderApp]=TRUE;"