宏后保留cutcopy模式

时间:2018-04-12 12:40:24

标签: excel vba excel-vba

所以我有这个问题,我无法解决这个问题。 我有一个excel报告,在sheet_activate上执行一个重要的宏,因为我们都知道宏取消了CutCopyMode。

因此,如果我想复制&将来自不同文件的内容粘贴到我的报告中,它永远不会起作用,因为只要我激活我的报告,它就会运行宏并从其他文件中取消CutCopyMode。

我尝试过的事情:

1)保存cutcopymode值并在宏之后重新激活它:

Dim tmpCT
tmpCT = Application.CutCopyMode

...

Application.CutCopyMode = tmpCT 

问题:它不起作用。

2)保存剪贴板中的数据,并在宏运行完毕后将其重新插入纯文本对象:

Dim DataClipBoard As String
Dim clipboardData As DataObject
Dim RangeCopied As Range
Set RangeCopied = Selection
DataClipBoard = ClipBoard_GetData
Application.CutCopyMode = False

...

Set clipboardData = New DataObject
With clipboardData
    .SetText DataClipBoard
    .PutInClipboard
End With
Set clipboardData = Nothing

问题:它是纯文本,不保留格式/链接/等。

我很感激你在这个问题上给我的任何意见。

1 个答案:

答案 0 :(得分:2)

以下宏将返回剪切/复制的当前范围,然后您可以将其存储在Range变量中,并在其他工作簿打开后重新剪切/复制。

(就我个人而言,我认为Function CutCopyRange() As Range Dim StoredMode As XlCutCopyMode StoredMode = Application.CutCopyMode If StoredMode < 1 Then Exit Function 'Null case If StoredMode = xlCut Then 'Disappointing, since Clipboard lets you Paste a copy of a cut range... MsgBox "Unfortunately, Worksheet.Paste(Link:=True) only works for Copy-mode.", vbCritical Exit Sub End If Dim ScreenUpdating As Boolean, DisplayAlerts As Boolean, EnableEvents As Boolean ScreenUpdating = Application.ScreenUpdating DisplayAlerts = Application.DisplayAlerts EnableEvents = Application.EnableEvents Application.ScreenUpdating = False Application.EnableEvents = False 'This makes us loose our Cut/Copy mode... With Worksheets.Add .Paste Link:=True Set CutCopyRange = Range(Range(Replace(Selection.Cells(1, 1).Formula, "=", "")), _ Range(Replace(Selection.Cells(Selection.Rows.Count, Selection.Columns.Count).Formula, "=", ""))) Application.DisplayAlerts = False .Delete End With 'Restore Cut/Copy mode to what it was before the previous block Select Case StoredMode Case xlCut CutCopyRange.Cut Case xlCopy CutCopyRange.Copy End Select Application.DisplayAlerts = DisplayAlerts Application.ScreenUpdating = ScreenUpdating Application.EnableEvents = EnableEvents End Function 应该是一个内置的特殊变量来执行此操作。)

lock(object1) {
    // do something 
    lock (object2) {
      // ...
    }

}