如何通过VBA / Excel

时间:2017-10-02 21:37:19

标签: excel vba excel-vba right-click

将以下代码添加到Excel中的 ThisWorkbook 对象后,它可以成功捕获当前工作簿中任何工作表的右键单击。

Private Sub Workbook_SheetBeforeRightClick(ByVal Sh As Object,  ByVal Target As Range, Cancel As Boolean)
   MsgBox "OK"
End Sub

但是,您能否建议是否可以从其他工作簿中捕获右键单击事件?

案例

有一个xlam文件来存储VBA项目的所有脚本。在xlam文件的 Thisworksheet 对象中,我添加了以下事件

'1) add popmenu when open any new workbook
' It works fine
Private Sub Workbook_Open()
    Call addPopMenu
End Sub

'2) delete popmenu when close a workbook
' It works fine
Private Sub WorkBook_Close()
    Call deletePopMenu
End Sub

'3) Capture the right-click event before displaying popmenu
'It does not work
Private Sub Worksheet_BeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
    'Call CheckPopMenu(Target) 'Aims to set the pop-menu based on the value in the cell
    MsgBox "OK"
End Sub

问题

通过 code(1)将弹出菜单成功添加到新的Excel工作簿中。遗憾的是,右键单击任何新的Excel工作簿时无法调用 code(3)。因此,我无法根据单元格中的值更新弹出菜单。

有没有让它有效?谢谢。

更新

Mat's Mug的建议效果很好。任何功劳都归功于Mat's Mug。

以下是我的工作代码,基于Mat's Mug的建议。希望它对那些困扰这个问题的人有所帮助

1)添加以下" xAppClass"类模块到VBA项目

Option Explicit
Public WithEvents ExcelAppEvents As Application

Private Sub Class_Initialize()
     Set ExcelAppEvents = Application
End Sub

Private Sub ExcelAppEvents_sheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
   Call CheckCellMenu(Target)  'replace with your own function
End Sub

2)将以下代码添加到模块

Public exlApp As New xAppClass

3)在The ThisWorkbook'对象,添加

Private Sub Workbook_Open()
    Set exlApp = New xAppClass
End Sub

添加上面的代码并运行" Workbook_open"例程,右键单击现在可以更新所有工作簿的工作表上的弹出菜单。

0 个答案:

没有答案