剪贴板偶尔在屏幕捕获循环中为空

Clipboard Occassionally is Empty on ScreenCapture Loop

我有一个执行以下任务的循环:

  1. 遍历一系列帐户,并点击每个帐户的网页
  2. 到达某个页面时,截屏该网页
  3. 将屏幕截图复制到 word 文档
  4. 打印word文档

大部分时间代码运行完美,但偶尔我在下面代码的 .Selection.Paste 行的处理过程中会出现以下错误:

Run-Time error '4605': This method or property is not available because the Clipboard is empty or not valid.

我试图通过在我的代码中放置一些 Sleep 命令并在每次复制/粘贴后清除剪贴板来解决问题。我的想法是,也许代码移动得太快,计算机需要时间来赶上,但无论我如何操纵它休眠了多少时间,我都无法得到停止在(看似)随机时间弹出的错误。

有没有人有任何想法来避免出现此错误?

代码如下:

'... code that loops through accounts and takes and actions against certain webpages until I get to the page I need to print

    Sleep 5000 'pause before screencapture takes place and make sure IE is active

    ScreenCapture

    Sleep 5000 'wait for screencapture to catch up ?

    With wApp 'wApp is a previously set variable that refers to MS Word
        .Visible = True
        .Documents.Add
        .Selection.Paste
        .PrintOut Range:=wdPrintCurrentPage
        .ActiveDocument.Close False
    End With

   Sleep 100   'wait for printing to finish ?

   ClearClipboard

   '... code continues to next account 

其他相关代码...

Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)
Public Declare Function OpenClipboard Lib "user32" (ByVal hwnd As Long) As Long
Public Declare Function EmptyClipboard Lib "user32" () As Long
Public Declare Function CloseClipboard Lib "user32" () As Long

Sub ScreenCapture()
 keybd_event VK_MENU, 0, 0, 0
 keybd_event VK_SNAPSHOT, 1, 0, 0
 keybd_event VK_SNAPSHOT, 0, KEYEVENTF_KEYUP, 0
 keybd_event VK_MENU, 0, KEYEVENTF_KEYUP, 0
End Sub

Public Function ClearClipboard()
    OpenClipboard (0&)
    EmptyClipboard
    CloseClipboard
End Function

另外注意:我试过直接打印 IE 页面,但由于与此无关的原因而无法正常工作post,但我想阻止任何建议改为这样做。

通常 DoEvents 可以在类似情况下提供帮助,在这种情况下,在 ScreenCapture 之前 And/Or 在 ClearClipboard

之后