gpt4 book ai didi

excel - 检查word文件是否已经打开vba

转载 作者:行者123 更新时间:2023-12-04 20:53:10 25 4
gpt4 key购买 nike

在打开 Word 文件之前,我想检查该文件是否已经打开。 (更多word文件同时打开)
主子调用这个函数来告诉我它是否打开。

Function FileInWdOpen(DokName As String) As Boolean                 

Dim wd As Word.Application
Dim wDoc As Word.Document

On Error Resume Next
Set wd = GetObject(, "Word.Application")
On Error GoTo NO_WORD_FOUND

If wd Is Nothing Then
FileInWdOpen = False
End If

For Each wDoc In wd.Documents 'should check for every open word file but doesn't do that
If wDoc.Name = DokName Then 'checks if this file is named like the one I want to check if its open or not
FileInWdOpen = True
Exit Function
End If
Next

FileInWdOpen = False

Exit Function

NO_WORD_FOUND:

FileInWdOpen = False

End Function

当只打开一个 word 文件时,此代码运行良好。如果打开了两个或更多文件,则脚本不起作用。

问题是 for 循环只检查第一个打开的文件。

我不明白为什么它不检查所有打开的文件。
我认为可以通过以下方式访问所有文档:
Dim WordApp As Word.Application                 'sets an var for the Word Application
Set WordApp = GetObject(, "Word.Application") 'give the var an obj, in this case the Word Application

Dim WordDoc As Word.Document 'sets an var for the singel Word Documents
For Each WordDoc In WordApp.Documents 'for each Document in Dokuments
'code
Next

那么为什么只有第一个文件得到关注呢?

最佳答案

这个可行 - 最后,我花了几个小时才找到解决方案。但我仍然错过了以下问题的答案:
我网络中的用户正在从服务器打开 Word 文件 - 我如何在 VBA 中找出哪个用户打开了(并保持打开状态)?

Function FileInWordOpen(DokName As String) As Boolean
Dim wd As Word.Application
Dim wDoc As Word.Document
Dim i As Long, s As String
On Error Resume Next
Set wd = GetObject(, "Word.Application")
On Error GoTo NO_WORD_FOUND
If wd Is Nothing Then
FileInWordOpen = False
End If
For i = 1 To wd.Documents.Count
s = wd.Documents(i)
If InStr(DokName, s) <> 0 Then
FileInWordOpen = True
Exit Function
End If
Next



'For Each wDoc In wd.Documents 'should check for every open word file but doesn't do that
' If wDoc.Name = DokName Then 'checks if this file is named like the one I want to check if its open or not
' FileInWdOpen = True
' Exit Function
' End If
'Next


NO_WORD_FOUND:

FileInWordOpen = False

End Function





Function GetOpenWordDoc(DokName As String) As Word.Document
Dim wd As Word.Application
Dim wDoc As Word.Document
Dim i As Long, s As String
On Error Resume Next
Set wd = GetObject(, "Word.Application")
On Error GoTo NO_WORD_FOUND
If wd Is Nothing Then
Set GetOpenWordDoc = Nothing
End If
For i = 1 To wd.Documents.Count
s = wd.Documents(i)
If InStr(DokName, s) <> 0 Then
Set GetOpenWordDoc = wd.Documents(i)
Exit Function
End If
Next


NO_WORD_FOUND:

Set GetOpenWordDoc = Nothing

End Function

关于excel - 检查word文件是否已经打开vba,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53501951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com