另一种方法不是覆盖Ctrl-V,而是使用上下文菜单。
在您要控制的工作表中,放置以下事件处理程序:
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
Dim tHasLock As Boolean
If IsNull(Target.Locked) Then ' at least one locked cell
tHasLock = True
Else
tHasLock = Target.Locked ' will only be true if the cell(s) are locked
End If
If tHasLock And Application.CutCopyMode <> False Then
Cancel = True
CommandBars("MyMenu").ShowPopup
End If
End Sub
如果有东西被剪切或复制并且单元格被锁定,这将激活。否则你会得到正常的菜单。
在您要创建“MyMenu”的工作簿中。您只能在应用程序中执行此操作一次,并且每次启动应用程序时都必须执行此操作。您可以在 Workbook_Open 上执行此操作。
Private Sub CreateMenu()
Dim tMyMenu As CommandBar
Dim tMenuItem As CommandBarControl
Set tMyMenu = Application.CommandBars.Add("MyMenu", msoBarPopup)
Set tMenuItem = tMyMenu.Controls.Add(ID:=370) ' Standard Paste values menu item
tMenuItem.Caption = "Paste &Values"
End Sub
应该发生的是,这将允许粘贴发生在锁定的单元格中。
在进一步测试中 - 这没有按预期粘贴(我将自己起草一个关于此的问题以用于其他目的,因为我为工作制作的特殊菜单确实会粘贴到锁定的单元格中!)。下面是一个替代方案。
Private Sub CreateMenu()
Dim tMyMenu As CommandBar
Dim tMenuItem As CommandBarControl
Set tMyMenu = Application.CommandBars.Add("MyMenu", msoBarPopup)
'Set tMenuItem = tMyMenu.Controls.Add(ID:=370) ' Standard Paste values menu item
'tMenuItem.Caption = "Paste &Values"
Set tMenuItem = tMyMenu.Controls.Add(msoControlButton)
With tMenuItem
.Caption = "Special Paste"
.OnAction = "PasteasValue" '"MySpecialPasteMacroName"
End With
End Sub
如果您已经创建了特殊菜单并尝试再次创建它,那么您将收到运行时错误(运行时错误“5”)。只需使用Application.CommandBars("MyMenu").Delete 就可以了。