繁体   English   中英

如何检查Word文件是否从Excel VBA打开?

[英]How to check if a Word file is open from Excel VBA?

我在谷歌中搜索了确切的术语,它吐出多个结果。 我尝试了至少 4-5 个。 没有工作。 根据 function,它要么全部为 TRUE,要么全部为 FALSE,但它永远不会正确。

除了不了解这些功能应该如何工作(这将是次要端点)之外,如果有人可以引导我到主要端点(检查 Word 文档是否从 Excel VBA 打开),我将非常感激?

谢谢

Word文件是否打开?

  • 如果 Word 应用程序未打开,则无法打开 Word 文件(在 Word 中)。
  • 所以首先检查Word是否打开,然后检查文件是否打开。

Word 打开了吗?

Function IsWordOpen() As Boolean
    Dim wdApp As Object
    ' Attempt to reference the word application.
    On Error Resume Next
        Set wdApp = GetObject(, "Word.Application")
    On Error GoTo 0
    IsWordOpen = Not wdApp Is Nothing
End Function

Sub IsWordOpenTEST()
    Debug.Print IsWordOpen
End Sub

参考字

Function RefWord() As Object
    Dim wdApp As Object
    ' Attempt to reference the word application.
    On Error Resume Next
        Set wdApp = GetObject(, "Word.Application")
    On Error GoTo 0
    If Not wdApp Is Nothing Then Set RefWord = wdApp
End Function

Sub RefWordTEST()
    ' Reference the word application.
    Dim wdApp As Object: Set wdApp = RefWord
    If wdApp Is Nothing Then
        MsgBox "Word is not open", vbExclamation
        Exit Sub
    End If
    ' Print the names of open files.
    Dim wdDoc As Object
    For Each wdDoc In wdApp.Documents
        Debug.Print wdDoc.Name
    Next wdDoc
End Sub

Word文件是否打开?

' Uses the RefWord function.
Function IsWordFileOpen( _
    ByVal WordFileName As String) _
As Boolean
    Dim wdApp As Object: Set wdApp = RefWord
    If wdApp Is Nothing Then Exit Function
    
    Dim wdDoc As Object
    On Error Resume Next
        ' Attempt to reference the word document.
        Set wdDoc = wdApp.Documents(WordFileName)
    On Error GoTo 0
    IsWordFileOpen = Not wdDoc Is Nothing
End Function

Sub IsWordFileOpenTEST()
    Debug.Print IsWordFileOpen("Test.docx")
End Sub

Word 文件是否打开(独立)?

  • 为什么我要在上面发布所有这些程序?
  • 当您运行以下命令时,如果结果为True ,那么您知道以下内容:
    • 话一开,
    • 名为Test.docx的文件已打开。
  • 您不知道的是它是正确的文件还是同名的另一个文件。
  • 如果结果为False ,情况会变得更糟,即您不知道以下内容:
    • Word是否打开
    • 是否有另一个 Word 实例打开了该文件
    • 另一个应用程序是否已锁定该文件,或者没有...
  • 总而言之,根据您打算如何处理这些信息,您必须决定要检查什么,即要小心,这只是一种基本方法。
' Stand-Alone
Function IsWordFileOpenCompact( _
    ByVal WordFileName As String) _
As Boolean
    Dim wdApp As Object
    ' Attempt to reference the word application.
    On Error Resume Next
        Set wdApp = GetObject(, "Word.Application")
    On Error GoTo 0
    If wdApp Is Nothing Then Exit Function
    
    Dim wdDoc As Object
    On Error Resume Next
        ' Attempt to reference the word document.
        Set wdDoc = wdApp.Documents(WordFileName)
    On Error GoTo 0
    IsWordFileOpenCompact = Not wdDoc Is Nothing
End Function

Sub IsWordFileOpenCompactTEST()
    Debug.Print IsWordFileOpenCompact("Test.docx")
End Sub

暂无
暂无

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

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