在Excel中复制粘贴操作时禁用格式

时间:2012-09-21 08:41:37

标签: excel vba excel-vba

我使用以下代码来禁用格式化复制粘贴操作时的格式化 -

Private Sub Worksheet_Change(ByVal Target As Range)
    With Application
        .EnableEvents = False
        myValue = Target.Formula
        .Undo
        Target.Formula = myValue
        .EnableEvents = True
    End With
End If
    Application.CutCopyMode = False
End Sub

代码很完美,但它在表格中插入了许多其他问题。

  1. 无法使用撤消/重做功能
  2. 无法在单击中更改单元格的焦点。
  3. 任何想法都会受到赞赏。

1 个答案:

答案 0 :(得分:0)

实质上,您希望禁止标准的粘贴,并可能通过粘贴特殊/值

替换它

您可以捕获粘贴功能并指定一条消息,告诉用户使用选择性粘贴/值,如

....
' place this in any suitable event trigger like 
Application.CommandBars("Edit").Controls("Paste").OnAction = "TrappedPaste"
....

Sub TrappedPaste()
    MsgBox "Your Paste is performed as PasteSpecialValues", vbOKOnly, "Paste"

    ' ok, now silently do a PasteSpecial/Values
    On Error GoTo TryExcel
    ' try to paste text
    ActiveSheet.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:=False
    Exit Sub
TryExcel:
    On Error GoTo DoesntWork
     Selection.PasteSpecial xlPasteValues
     Exit Sub
DoesntWork:
    MsgBox "Sorry - wrong format for pasting", vbExclamation + vbOKOnly, "Paste Problem"
 End Sub

Carefull ...这不适用于所有语言,因此对于国际申请,我们需要更加低级

If ExistControl("Edit", 22) Then Application.CommandBars("Edit").FindControl(ID:=22).OnAction = "TrappedPaste"

在应用程序中有更多地方可以让用户从中获取“粘贴”,你需要将它们全部捕获。

如果您喜欢这种方法,我可以进一步详细说明。