剪贴板偶尔在ScreenCapture循环上为空

时间:2015-10-26 16:44:50

标签: vba access-vba clipboard word-vba screen-capture

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

  1. 循环浏览一系列帐户,并点击每个帐户的网页
  2. 当它到达某个页面时,捕获网页的屏幕
  3. 将屏幕截图复制到word文档
  4. 打印word文档
  5. 大部分时间代码都能正常运行,但偶尔我会在下面代码中.Selection.Paste行的处理过程中遇到以下错误:

      

    运行时错误'4605':   此方法或属性不可用,因为剪贴板为空或无效。

    我尝试通过在代码中放入一些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页面,但由于与此帖子无关的原因而无效,但我想阻止任何建议。

1 个答案:

答案 0 :(得分:1)

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