I'm writing a program under Excel that generate a lot of spreadsheets by copying / pasting some data from one worksheet to another (example: using a "Layout" worksheet with some header / footer cells which will be copied/pasted to the generated worksheets).
My problem is that, some times (not every time), when running my "generation process", Excel generate this error (sorry this is an English translation from my french Excel error) :
Error 1004 : The 'Paste' method of the '_Worksheet' object has failed
So I'm assuming that there is a problem with the Clipboard (with other software on my computer which probably used the clipboard at the same time :/)
I firstly try to find a way to copy/paste my cells (and other stuff) without using the clipboard, with code like that :
ThisWorkbook.Sheets("Layout").Range("A1").Copy Destination:=ThisWorkbook.Sheets("Test").Range("A1")
or that
ThisWorkbook.Sheets("Test").Range("A1") = ThisWorkbook.Sheets("Layout").Range("A1")
But it seems that we can only copy text or formula, not all the stuff (border, color,...) and also not Chart object (I have ones)!
So I try to find a way to lock/unlock the clipboard during the copy/paste. I found this code to do that:
Declare Function OpenClipboard Lib "user32" (ByVal hwnd As Long) As Long
Declare Function CloseClipboard Lib "user32" () As Long
Declare Function EmptyClipboard Lib "user32" () As Long
Public Sub Lockk()
If OpenClipboard(0) = 0 Then
MsgBox "cannot open clipboard."
ElseIf EmptyClipboard() = 0 Then
MsgBox "cannot clear clipboard."
End If
End Sub
Public Sub Unlockk()
CloseClipboard
End Sub
It seems working when copying cells: I can lock the clipboard under excel, go to another software (notepad for example), and can't copy paste some data into this software; go back to excel and I can copy/paste data (manually or with a macro).
But:
It seems that pasting a cell will unlock the clipboard (I can lock, go to notepad, notepad has not access to the clipboard, go back to excel, copy/paste a cell, go back to notepad, and then the notepad can access to the clipboard; and I have not unlock explicitly the clipboard). That is not really a problem for me.
After locking the clipboard, we can't copy/past a Chart object (manually or with a macro). With a macro, I get exactly the same error as before).
So, is someone as an idea about how to lock/unlock the clipboard to copy chart object? Or to copy them without using the clipboard?
Edit:
The code used to copy/paste the graph object:
Utils_Clipboard.Lockk
ThisWorkbook.Sheets("Layout").ChartObjects("CHART_TEMPLATE").Copy
DoEvents
worksheet_p.Paste Destination:=where_p
Utils_Clipboard.Unlockk
where worksheet_p is a Worksheet object, adn where_p is a range. Note that without the first and last lines (Lockk the clipboard), it's working fine (except some time).