CopyPicture method of range class failed - sometimes
i have found a way to force excel to wait until the clipboard has a picture in it, because sometimes it's too fast:
Private Declare PtrSafe Function IsClipboardFormatAvailable Lib "user32" (ByVal wFormat As Long) As LongDeclare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) 'just after copypicture, add this: (in my case i added it inside pastepicture, or i'd have too much coding )Dim T# Do Waiting (2)Loop Until IsClipboardFormatAvailable(2) Or Timer - T > 0.3Sub Waiting(ByVal Mili_Seconds&)Sleep Mili_SecondsEnd Sub
I was struggling with the very same issue than you and I think is nothing to do with our VBA code or lack of programming skills. The error it's too random.
Moreover, if after getting the error message I clicked DEBUG and pressed F8 to continue executing the code step by step, then I was able to skip the error. After the problematic line I pressed F5 to continue in normal execute mode.
Of course, the above is not a solution but reveals nothing wrong with my coding.
Well, I did this and it worked for me:
before this sentence,
rgToPic.CopyPicture Appearance:=xlScreen, Format:=xlBitmap
I added this one:
rgToPic.Copy 'just for nothing
and I never have had the error in CopyPicture
method again.
Looking for this issue in other places I found out some users were able to skip the error by introducing this sentence before the CopyPicture
method:
application.CutCopyMode=false
The only thing that worked for me was to add a delay BEFORE the CopyPicture method. We are tweaking it shorter as I type this, but I know a 50 ms delay was working fine:
Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
'Set Range you want to capture
Dim rgExp As Range: Set rgExp = Range("B2:D6")
Sleep (50) ' Pause in milliseconds to prevent runtime error on CopyPicture, your system may be able to use shorter sleep, or may need longer...
' Copy range as picture onto Clipboard
rgExp.CopyPicture Appearance:=xlScreen, Format:=xlBitmap