So I have this problem which I can’t wrap my head around.
I have a an excel report that executes an important macro on sheet_activate, and as we all know macros cancel CutCopyMode.
Therefore, if I want to copy & paste something from a different file into my report, it never works because as soon as I activate my report it runs the macro and cancels the CutCopyMode from the other file.
Things I have tried:
1) save cutcopymode value and re-activate it after the macro:
Dim tmpCT tmpCT = Application.CutCopyMode ... Application.CutCopyMode = tmpCT
the problem: it doesnt work.
2) save the data from the clipboard and re-insert it as plain text object after the macro is done running:
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
The problem: it’s plain text and doesn’t retain formats/links/etc.
I’d appreciate any input you can give me on this issue.
The following macro will return the current range for Cut/Copy, which you can then store in a Range variable and re-Cut/Copy after your other workbook is open.
(Personally, I think that
Application.CutCopyRange should be a built-in special variable to do this.)
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