Clipboard “copy” selection gone when autosizing VBA button?

安稳与你 提交于 2019-12-25 02:55:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!