我的问题中的代码受到这个问题提供的答案中的解决方案的启发: How to add a menu item to the default right click context menu
我在表单上有一个ListBox对象,显示了一系列Actions。我希望用户能够右键单击此列表中的项目以显示上下文菜单,他可以在其中:
Private Sub List_actions_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single
'set up commandBar
Dim combo As CommandBarControl
'Since it may have been defined in the past, it should be deleted,
'or if it has not been defined in the past, the error should be ignored
On Error Resume Next
CommandBars("RCActionContextMenu").Delete
On Error GoTo 0
'Make this menu a popup menu
With CommandBars.Add(Name:="RCActionContextMenu", Position:=msoBarPopup)
Set combo = .Controls.Add(Type:=msoControlButton)
combo.BeginGroup = True
combo.Caption = "View action" ' Add label the user will see
combo.OnAction = "List_actions_DblClick" 'Add the name of a function to call
Set combo = .Controls.Add(Type:=msoControlButton)
combo.Caption = "Delete action"
combo.OnAction = DelAction()
End With
If Button = acRightButton Then
DoCmd.CancelEvent
CommandBars("RCActionContextMenu").ShowPopup
End If
End Sub
Public Function DelAction()
If Not IsNull(Me.Controls("RCActionContextMenu").Column(0)) Then
CurrentDb.Execute "DELETE * FROM T_ACTIONS " & _
"WHERE ID = " & List_actions.Column(9) & ";"
MsgBox "Action supprimée", vbInformation, "Information"
End If
End Function
Private Sub List_actions_DblClick(Cancel As Integer)
Dim vStatus As String
'Get the record's index of the action
rowNumber = Me.List_actions.ListIndex + 1
id_action = List_actions.Column(9, rowNumber)
vStatus = List_actions.Column(5, rowNumber)
'Open the action
DoCmd.OpenForm "F_ACTIONS", , , "[ID] = " & List_actions.Column(9)
Form_F_ACTIONS.Effective_date.Visible = Effdatefunction(vStatus)
End Sub
我得到的问题是DelAction()函数在显示弹出窗口之前执行,我得到一个run-time error 2465
说明"Microsoft Access can't find the field 'RCActionContextMenu' referred to in your expression."
我试过用combo.OnAction = DelAction()
重新排列combo.OnAction = "DelAction"
行。它会导致conextual菜单显示自己,但是当我点击任一按钮时没有任何反应。
这里有一些问题。
combo.OnAction = DelAction()
正如您所见,这将调用该函数。你需要在这里设置一个字符串。
combo.OnAction = "DelAction()"
这仍然不起作用,因为DelAction()
在你的表单模块中。
将函数移动到带有参数的公共模块,或者将对象名称硬编码到那里,
combo.OnAction = "DelAction(""MyFormName"", ""List_actions"")"
或尝试(不确定这是否有效):
combo.OnAction = "Form_YourFormName_DelAction()"
它与"List_actions_DblClick"
相同 - 该函数需要从“外部”调用,就像立即窗口一样。
If Not IsNull(Me.Controls("RCActionContextMenu").Column(0)) Then
你的上下文菜单命令栏不是一个控件,你想要的是列表框:
If Not IsNull(Me.Controls("List_actions").Column(0)) Then
或者干脆
If Not IsNull(Me!List_actions.Column(0)) Then
删除操作后,您需要重新查询列表框。
CurrentDb.Execute "DELETE * FROM T_ACTIONS " ...
Me!List_actions.Requery