MS Access:我的表单的vba中的错误

spo*_*dem 5 ms-access vba

我有一个简单的MS Access表单,有3个对象:文本框,列表框和按钮.表单的预期用途如下:用户在文本框中输入名称,从列表框中选择一个项目,然后单击按钮将数据添加到表格中.

但是,当我单击按钮时,我不断收到错误消息,"除非控件具有焦点,否则无法引用属性或控件的方法."

以下是我的代码.谢谢!

Private Sub addRecord_button_Click()
    Dim CustomerName As String
    Dim CustomerType As String

    On Error GoTo Errhandler

    CustomerName = "[name not selected]"
    CustomerType = "[type not selected]"

    CustomerName = Customer_TextBox.Text

    Select Case Type_ListBox.ListIndex
        Case 0
            CustomerType = "Type 1"
        Case 1
            CustomerType = "Type 2"
        Case 2
            CustomerType = "Type 3"
    End Select

    'MsgBox ("Name: " & CustomerName & " and Type: " & CustomerType)

    DoCmd.RunSQL "INSERT INTO Customer VALUES (CustomerName, CustomerType);"

Errhandler:
    MsgBox ("The following error has occured: " & Err & " - " & Error(Err))
End Sub
Run Code Online (Sandbox Code Playgroud)

Har*_*til 9

.Text只有在TextBox具有焦点时才能使用该属性.请尝试使用该.Value属性.

尝试更换以下行

CustomerName = Customer_TextBox.Text
Run Code Online (Sandbox Code Playgroud)

CustomerName = Customer_TextBox.Value
Run Code Online (Sandbox Code Playgroud)

  • 或者,完全遗漏一个属性,即"我!Customer_Textbox"(也确实应该指定父形式,即Me !,因为它将它与对变量的引用区分开来). (2认同)