简体   繁体   English

MS Word中的VB宏

[英]VB macro in MS word

The following code works as intended when I open word then open my test document. 当我打开word然后打开测试文档时,以下代码将按预期工作。 However, if I open the test document to start the first instance of Word, the timer kicks off while Word is loading up. 但是,如果我打开测试文档以启动Word的第一个实例,则在Word加载时计时器启动。 Word then sits at loading till the timer runs out, document closes and a empty Word application is opened. 然后,Word处于加载状态,直到计时器用尽,文档关闭并打开一个空的Word应用程序。 The intended operation is open document; 预期的操作是打开的文档; if idle for set time, save and close document. 如果闲置了设定的时间,请保存并关闭文档。

I have users that share a document and same have a bad habit of locking their computer with the doc open, locking the file from anyone else editing it. 我有共享文档的用户,并且有一个坏习惯,那就是在打开文档时锁定他们的计算机,并从其他任何编辑它的人那里锁定文件。 the goal of this is to save the file and close the doc after x time. 这样做的目的是保存文件并在x时间后关闭文档。

Private Sub Document_open()
 StartCheckingIdle
End Sub

The TIMEOUTTIME below is set to 5 seconds for testing, but set it to 5 min say, and the document just sits at loading for that five minutes if Word was not open prior to double clicking the document to open. 下面的TIMEOUTTIME设置为5秒以进行测试,但是将其设置为5分钟,如果在双击文档以将其打开之前未打开Word,则该文档仅处于加载状态五分钟。

Option Explicit

'Set the constant below for how long you want it to be idle before triggering
' Enter the time in hours:minutes:seconds form, like "00:30:00" for 30 minutes
Private Const TIMEOUTTIME As String = "00:00:05"

Private Declare Function GetQueueStatus Lib "user32" (ByVal fuFlags As Long) As Long
Private Const QS_KEY = &H1
Private Const QS_MOUSEMOVE = &H2
Private Const QS_MOUSEBUTTON = &H4
Private Const QS_MOUSE = (QS_MOUSEMOVE Or QS_MOUSEBUTTON)
Private Const QS_INPUT = (QS_MOUSE Or QS_KEY)
Private bCancel As Boolean
Private Sub WaitForIdle()
 Dim t As Double
 t = Now
 Do While bCancel = False
  If GetQueueStatus(QS_INPUT) Then
   t = Now
   DoEvents
  End If
  If Now - t >= TimeValue(TIMEOUTTIME) Then Exit Do
 Loop
End Sub
Public Sub StartCheckingIdle()
 Do Until bCancel
  WaitForIdle
  If bCancel = False Then
   bCancel = True
   ThisDocument.Close True
  End If
  Do Until GetQueueStatus(QS_INPUT) Or bCancel
   DoEvents
  Loop
 Loop
End Sub
Public Sub StopCheckingIdle()
 bCancel = True
End Sub

Currently trying to get working on a Word doc, but eventually will need to apply this to an excel file as well. 目前正在尝试处理Word文档,但最终还需要将其应用于excel文件。 Yes, I burrowed this code from another question on here, though I think it might be slightly outdated. 是的,我从这里的另一个问题探究了此代码,尽管我认为它可能有些过时了。 I am running Office 2010. 我正在运行Office 2010。

May try to check for an active window first in your document. 可以尝试首先在文档中检查活动窗口。

Private Sub Document_Open()
    Do While Application.ActiveWindow.Active = False
        DoEvents
    Loop
    MsgBox "Open"
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM