Search code examples
excelvbaoutlookscreenshot

Runtime error 1004 : paste method of worksheet class failed after Screenshot


I am trying to screenshot certain application and paste to excel sheet by using AppActivate and Sendkeys 1068, however sometimes, I receive a 1004 error on Activesheet.Paste,

"Paste method of Worksheet class failed".

Sometimes the macro works. I cannot pinpoint why this happens.

Can anyone identify issues with the code? Clearing the clipboard with Application.CutCopyMode = False works sometimes, but not always.

Sub testscreenshotplusemail()

Dim r As Range
Dim outMail As Outlook.MailItem
Dim wordDoc As Word.Document
Dim count As Integer

AppActivate ("TESTING")

Application.CutCopyMode = False

Application.SendKeys "(%{1068})"

DoEvents

Application.Wait (Now + TimeValue("00:00:02"))

Range("A5").Select

ActiveSheet.Paste

For Each pic In ActiveSheet.Pictures
count = count + 1
Next pic

If count = 0 Then
Exit Sub
End If

Set r = Range("A12:F37")
r.Copy

Dim outlookApp As Outlook.Application
Set outlookApp = CreateObject("Outlook.Application")
Set outMail = outlookApp.CreateItem(olMailItem)

SelectionBehalf = Worksheets("Sheet1").Range("F3").Value
SelectionTO = Worksheets("Sheet1").Range("G3").Value
SelectionCC = Worksheets("Sheet1").Range("H3").Value
SelectionSubj = Worksheets("Sheet1").Range("I3").Value
SelectionBody = Worksheets("Sheet2").Range("F2").Value

With outMail
.SentOnBehalfOfName = SelectionBehalf
.Display
.To = SelectionTO
.CC = SelectionCC
.Subject = SelectionSubj
.Body = SelectionBody

Set wordDoc = outMail.GetInspector.WordEditor

wordDoc.Range(Start:=wordDoc.Range.End - 1).PasteAndFormat wdChartPicture


End With

For Each pic In ActiveSheet.Pictures
pic.Delete
Next pic
Application.SendKeys "{NUMLOCK}"
Application.CutCopyMode = False

End Sub

Solution

  • Using SendKeys is a reliable way of programming. Use Windows API functions instead of relying on keyboard commands where other software or applications may prevent from successfully running the code. See How to do a screen capture using VBA for more information.