MS Access: An error in vba of my form

2020-04-06 06:51发布

I have a simple MS Access form that has 3 objects: a text box, a list box, and a button. The intended use of the form is as follows: the user enters a name in the text box, selects an item from the list box, then clicks the button to add the data to a table.

However, when I click on the button, I keep getting the error message, "You can't reference property or a method for a control unless the control has the focus."

Below is my code. Thanks!

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

标签: ms-access vba
1条回答
Lonely孤独者°
2楼-- · 2020-04-06 07:35

The .Text property can only be used when the TextBox has focus. Try using the .Value property instead.

Try replacing the below line

CustomerName = Customer_TextBox.Text

with

CustomerName = Customer_TextBox.Value
查看更多
登录 后发表回答