也许今天早上我只是在Googles上表现糟糕,但是我很快就在VBA中找到一个事件处理程序,用于在从其他应用程序切换时激活工作簿.我正在使用Excel 2010.
在ThisWorkbook对象中,我尝试了以下内容:
Private Sub Workbook_Activate()
MsgBox "1"
End Sub
Private Sub Workbook_WindowActivate(ByVal Wn As Window)
MsgBox "2"
End Sub
Run Code Online (Sandbox Code Playgroud)
在类模块中,我尝试过这些:
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
Run Code Online (Sandbox Code Playgroud)
这里的最终结果是在激活此工作簿(单击或alt-tabbed-to)时禁用CellDragAndDrop属性,并在此工作簿未处于活动状态时重新启用它.可能是我想念的简单事情,但我厌倦了这一点.谢谢!
好吧,我一开始以为这是功能区定制的工作。我无法使用功能区执行此操作(并不是说这是不可能的,但我没有看到任何会影响此功能的命令MSO)。
您的类模块就像这样(我没有尝试您列举的其他视图状态)。该模块封装了事件类并包含应用程序级事件处理程序。为此,我认为您可能只需要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
Run Code Online (Sandbox Code Playgroud)
在名为 的标准模块中使用以下内容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
Run Code Online (Sandbox Code Playgroud)
将其放入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
Run Code Online (Sandbox Code Playgroud)
注意:如果您“结束”运行时或在调试时执行任何可能导致状态丢失的操作,您将丢失事件处理程序。这始终可以通过调用 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
Run Code Online (Sandbox Code Playgroud)
我已经在我的Google Docs上提供了我的文件的副本,以防万一上面提供的代码中存在一些错误的拼写错误。
| 归档时间: |
|
| 查看次数: |
4959 次 |
| 最近记录: |