An alternate approach is not to over-ride Ctrl-V
but to use a context menu.
Within the worksheet that you want to control, place the following event handler:
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
This will activate if there is something been cut or copied and the cell is locked. Otherwise you will get the normal menu.
Within the workbook you want to create "MyMenu". You can only do this once within the Application, and will have to do it each time you start the application. You could do this on 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
What should happen is that this will allow the paste to happen in the locked cells.
On further testing - this does not paste as expected (I will be drafting a question about this myself for other purposes, because a special menu I have made for work does paste into locked cells!). An alternative is below.
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
If you have already created the special menu and you try to create it again, then you will get a run-time error (run time error '5'). Just use Application.CommandBars("MyMenu").Delete
and you will be good to go.
PastAsValues() Selection.PasteSpecial Paste:=xlPasteValues End Sub
it allows me to paste in locked cells. this is what I want to prevent - basically getting back the standard check/error message – Nico