问题
I´m puzzled that Excel throws away the clipboard "copy" selection for no (obvious) reason when creating an auto-sized button.
Consider this simple selection change handler:
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Excel.Range)
Dim P As Button: Set P = ActiveSheet.Buttons.Add(1, 1, 100, 100)
End Sub
This simple creates a dumb button on the top left corner of the sheet on every cell selection change.
If you press Ctrl-C in any cell (no matter if it´s empty or not), the cell will have this nice border indicating that the selection is what will be pasted if you select paste elsewhere.
That border will remain visible even if you navigate around on the sheet.
Now add one line:
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Excel.Range)
Dim P As Button: Set P = ActiveSheet.Buttons.Add(1, 1, 100, 100)
P.AutoSize = True
End Sub
This makes the button(s) autosize themselves. Works fine. But from know on, every selection change will destroy the clipboard "copy" selection.
- Why? Can I prevent this, or work around it?
Reproduced with Excel 10 14.0.7116.5000 32-bit :-O
回答1:
If you have copied content then you will need to paste it before anything else happens. This is how Excel behaves naturally.
So, in your event, you can Paste the content (to the currently active cell) before Auto-Sizing the button.
Dim P As Button
If Application.CutCopyMode = xlCopy Then
Me.Paste
End If
Set P = ActiveSheet.Buttons.Add(1, 1, 100, 100)
'Application.EnableEvents = False
P.AutoSize = True
'Application.EnableEvents = True
EnableEvents
is unnecessary here, but I've included it to indicate how you might prevent an event from triggering a second time. You probably need to work with it at some point.
来源:https://stackoverflow.com/questions/23833050/clipboard-copy-selection-gone-when-autosizing-vba-button