Excel 2010 VBA – 用于在应用程序之间切换的事件处理程序?

也许我今天早上在Google上只是很糟糕,但我在VBA中find一个事件处理程序,用于在从其他应用程序切换时激活工作簿。 我正在使用Excel 2010。

在ThisWorkbook对象中,我尝试了以下方法:

Private Sub Workbook_Activate() MsgBox "1" End Sub Private Sub Workbook_WindowActivate(ByVal Wn As Window) MsgBox "2" End Sub 

在一个类模块中,我试过这些:

 Public WithEvents appevent As Application Private Sub appevent_ProtectedViewWindowActivate(ByVal Pvw As ProtectedViewWindow) MsgBox "1" End Sub Private Sub appevent_ProtectedViewWindowOpen(ByVal Pvw As ProtectedViewWindow) MsgBox "2" End Sub Private Sub appevent_WindowActivate(ByVal Wb As Workbook, ByVal Wn As Window) MsgBox "3" End Sub Private Sub appevent_WorkbookActivate(ByVal Wb As Workbook) MsgBox "4" End Sub Private Sub appevent_WorkbookDeactivate(ByVal Wb As Workbook) MsgBox "5" End Sub 

最终结果是在激活此工作簿(单击或replace选项卡)时禁用CellDragAndDrop属性,并在此工作簿不活动时重新启用它。 可能是我错过了一些简单的事情,但是我对这件事感到厌倦。 谢谢!

好的,我认为这是第一个function区定制的工作。 我不能用Ribbon来做(不是说这是不可能的,但是我没有看到任何会影响这个function的commandMSO)。

你的类模块是这样的(我没有试验过你列举的其他视图状态)。 该模块封装了事件类,并包含应用程序级事件处理程序。 为此,我认为你可能只需要WorkbookActivate 。 引发事件的工作簿将决定是否启用/禁用该属性。

 Public WithEvents appevent As Application Dim ret As String Private Sub appevent_WorkbookActivate(ByVal wb As Workbook) Call ToggleDragAndDrop(wb, ret) 'Comment out this line when satisfied it is working as expected MsgBox "Cell drag & drop enabled = " & ret End Sub 

在名为mod_DragDrop的标准模块中使用以下mod_DragDrop

 Option Explicit Public XLEvents As New cEventClass Sub SetEventHandler() If XLEvents.appevent Is Nothing Then Set XLEvents.appevent = Application End If End Sub Sub ToggleDragAndDrop(wb As Workbook, Optional ret$) Application.CellDragAndDrop = (wb.Name <> ThisWorkbook.Name) ret = Application.CellDragAndDrop End Sub 

把这个放在Workbook_Open事件处理程序中:

 Option Explicit Private Sub Workbook_Open() 'Create the event handler when the workbook opens Call mod_DragDrop.SetEventHandler Call mod_DragDrop.ToggleDragAndDrop(Me) End Sub 

注意:如果“结束”运行时或在debugging时执行任何会导致状态丢失的事情,则将丢失事件处理程序。 这总是可以通过调用Workbook_Open过程来恢复,所以在ThisWorkbook代码模块中也可以添加一个额外的保护措施:

 Private Sub Workbook_SheetActivate(ByVal Sh As Object) ' Additional safeguard in case state loss has killed the event handler: ' use some workbook-level events to re-instantiate the event handler Call Workbook_Open End Sub 

我已经在我的Google文档中提供了我的文件的副本,以防上面提供的代码中出现错误的拼写错误。