excel - 检查word文件是否已经打开vba
问题描述
在打开 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
推荐阅读
- python - 在 Windows 10 系统上安装 Selenium Python 客户端时连接到 pypi.org 超时错误
- python - 用什么代替input()
- google-analytics - 谷歌分析没有记录自定义维度
- python - 如何根据另一列的值在 pandas 中获取新列?
- java - Java/Spring:如何使用 TransactionSynchronizationManager 指定嵌套事务的顺序
- javascript - TypeScript 表达式解释
- sql - sqlite支点?结果行作为列
- php - 使用 ACF 对嵌套转发器字段输出进行分组
- oracle - ORA-01747 错误 user.table.column、table.column 或列规范无效
- nativescript - 如何在 Nativescript-Vue 中使用 nativescript-drawingpad?