Experiencing problems with copy/paste excel objects/shapes with VBA

馋奶兔 提交于 2020-07-09 17:54:29

问题


I have some complex code which takes some user inputs (names of shapes to copy) then copies said shapes from one sheet to another multiple times. The items are grouped shapes drawn in Excel and all named correctly and uniquely.

I receive copy and paste errors intermittently "Method 'Paste' of object _Worksheet' failed" and "Method 'copy' Of Object '_worksheet' Failed. Through researching the problem we understand that it is fairly common and has something to do with programmes which conflict with Excel when they are accessing the clipboard.

So far, my colleague and I have deduced that 2 programmes in particular interfere the most with the copy/paste operations - Adobe Reader and Autodesk Powershape. (Autodesk and Adobe both have Reference Libraries available within VBA, not sure if this is a coincidence?)

The problem used to occur very frequently whilst we had the programmes open, so we wrote the following macros/functions to try and stablise the code:-

Public Sub CopyShape(ItemName, CopyDestination)

Call ClearClipboard Sheets(CopyDestination).Shapes(ItemName).Copy 

Do Until IsClipboardEmpty = False DoEvents Loop

End Sub

Where "ClearClipboard" is:-

Public Function ClearClipboard() 

OpenClipboard (0&) 

EmptyClipboard

CloseClipboard 

End Function

and the function IsClipboardEmpty is:-

Function IsClipboardEmpty() As Boolean 

IsClipboardEmpty = (CountClipboardFormats() = 0) 

End Function

with the following public declarations:-

Declare Function OpenClipboard Lib "user32" (ByVal hwnd As Long) As Long 

Declare Function EmptyClipboard Lib "user32" () As Long 

Declare Function CloseClipboard Lib "user32" () As Long

Public Declare Function CountClipboardFormats Lib "user32" () As Long

This code works quite a lot of the time (far better than trying to use "DoEvents" after the copy operation which just failed miserably) as it forces the code to check if the copied item is in the clipboard before trying to paste it, but it doesn't always work - something in the background still messes up the code.

Is there any way of either:-

  • locking and unlocking the clipboard using VBA or APIs?
  • using a completely different method of copying and pasting the shapes?

Any and all solutions welcome and of course happy to answers any questions.

Thanks

来源:https://stackoverflow.com/questions/51285401/experiencing-problems-with-copy-paste-excel-objects-shapes-with-vba

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