OK I thought this was a job for Ribbon customization at first. I'm not able to do it with the Ribbon (not to say it is not possible, but I don't see any commandMSO's that would affect this functionality).
Your class module like so (I did not experiment with the other view states that you had enumerated). This module encapsulates the event class and contains the application-level event handlers. For this purpose, I think you might only need the WorkbookActivate
. The workbook raising the event will determine whether to enable/disable that property.
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
Use the following in a standard module named 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
Put this in the Workbook_Open
event handler:
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
Note: If you "end" run-time or do anything while debugging which would cause state loss, you will lose the event handler. This can always be restored by calling the Workbook_Open procedure, so an additional safeguard might be to add this also in the ThisWorkbook
code module:
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
I have made a copy of my file available on my Google Docs, just in case there is some errant typo in the code provided above.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…