Home » excel » vba – Intercept "Paste" event on Shared workbook and run a macro

vba – Intercept "Paste" event on Shared workbook and run a macro

Posted by: admin April 23, 2020 Leave a comment

Questions:

I would like to run a certain procedure (macro) when a user is trying to paste an image on a sheet of my workbook.

If the user would be just pasting a simple text into the sheet of a non-shared workbook, then I could easily detect the event via the Workbook_SheetChange of the Worksheet_Change (with some tricks to understand that it was a “Paste” event and not a simple text manual typing).

However, here the complexity is added by two factors:

  • If I paste an image, the event Worksheet_Change is not triggered even when the workbook is not shared;
  • In shared workbooks is impossible to paste images. Hence, Excel’s native’s code seems to stop the action even before the event could be detected.

Does anyone have any idea (even including Windows API to intercept clipboard actions)?

How to&Answers:

If it can help anyone, I’ve finally solved the above with a “not very nice but working solution”:

On Workbook_Open, I’ve added a listener for the Ctrl+v key that will not perform the usual paste but rather will call a separate macro:

Application.OnKey "^{v}", "mySpecialPaste"

The code of mySpecialPaste being:

MakeExclusive '<-- procedure to make the workbook exclusive
Application.OnKey "^{v}" '<-- remove the "Ctrl+V" link to the macro
Application.SendKeys "^{v}" '<-- send a Ctrl+V to perform the paste
Application.OnKey "^{v}", "mySpecialPaste" '<-- re-link the Ctrl+V to this macro
MakeShared '<-- make the workbook shared once again

Of course it’s not an elegant solution since it relies on the fact that the user performs the paste of the picture using the Ctrl+V key and not, for example, a right click / paste. Plus, this will be triggered on any Ctrl+V (even if the user is just pasting normal text, which is a normal action even on a shared workbook). Finally, it relies on the SendKeys which is well known to be not very nice (not reliable, not stable).

However, it was satisfying for my specific use case so I’ve thought about sharing it as an answer since none has thought to a better solution so far.