Search code examples
ms-accessvbams-access-2016

why is my VBA code not working


I got a listbox with numbers in it and a button, i want the listbox to show the number you selected in another form

example i want to buy a number of keys from 1 to 10 if i select 3 i want the next form to show you bought 3 keys

Private Sub List28_Click()
If Not IsNull([num of keys]) Then
Forms! [navigation forms].Form.[navigationsubform].Form.User = 
Me.Num_of_keys_Label
Forms! [navigation forms].Form.[navigationsubform].Form.User = Me.List28
End If
DoCmd.Close
EndSub

showing the result if a purchase

i get a compile error: invalid use of property


Solution

  • This is not VBS (Microsoft Visual Basic Scripting Edition). It is VBA (Visual Basic for Applications). VBA is line oriented. If you want to split a long line, you must use a line continuation character preceeded by a space (_) at the end of the line.

    Forms! [navigation forms].Form.[navigationsubform].Form.User = _
        Me.Num_of_keys_Label
    

    There should be a space in EndSub

    End Sub
    

    Also, indenting the code makes it more readable

    Private Sub List28_Click()
        If Not IsNull([num of keys]) Then
            Forms![navigation forms].Form.[navigationsubform].Form.User = _
                Me.Num_of_keys_Label
            Forms![navigation forms].Form.[navigationsubform].Form.User = Me.List28
        End If
        DoCmd.Close
    End Sub
    

    You should use the AfterUpdate event. Not the Click event. AfterUpdate occurs after a new item has been selected.

    What is [num of keys]? The name of the listbox seems to be List28.

    List28 is a bad name. Rename your controls before creating the event methods. This makes the code more readable. E.g. If you rename the listbox to lstNumbers, then you get a speaking name for the event method like lstNumbers_AfterUpdate. A name like btnCancel_Click is easier to understand than Button17_Click.

    I don't understand the logic of the code. You set the User control (a Label or a TextBox?) of the other form to Me.Num_of_keys_Label instead of [num of keys] which you tested to be not null. Immediately afterwards you replace this value by Me.List28, which is, according to your comment ("the click was for the button"), a button. This all makes no sense.

    Start by prefixing the names of controls and forms. E.g.

    txt for TextBoxes, e.g. txtUser
    btn for Buttons, e,g, btnBuy
    lst for ListBoxes, e,g, lstNumOfKeys
    lbl for Labels, e,g, lblResult
    cbo for ComboBoxes, e,g, cboCountry
    frm for Forms, e,g, frmNavigation
    fsub for subform controls, e,g, fsubNavigation