[英]Opening doc or docx in word with vba
我想打开一个Word文档以专用,但是我的代码有时会失败。 我们有几种情况:
后两种情况在我的函数中应返回false。
Function OpenDocument(filename As String) As Boolean
Dim found As Boolean
Dim doc As Object
Dim fileNameCorrected As String
found = False
OpenDocument = True
'need to figure out if its docx or doc or
fileNameCorrected = Dir(GetFileNameWithOutExtension(filename) & ".do*")
filename = FileHandling.GetFolder(filename) & fileNameCorrected
If fileNameCorrected <> "" Then
For Each doc In Documents
If doc.name = fileNameCorrected Then
found = True
Exit For
End If
Next doc
If found <> True Then
' \\ Only open File if the file is not opened yet
If Not IsFileLocked(filename) Then
Documents.Open filename:=filename
Else
OpenDocument = False
Exit Function
End If
End If
Documents(fileNameCorrected).Activate
Else
'MsgBox "File doesn't exist. Sorry check ur settings mate"
OpenDocument = False
End If
End Function
但是有时它在这里失败
If Not IsFileLocked(filename) Then
Documents.Open filename:=filename
Else
奇怪的是,当文档已经打开时,它会跳到那里–无法正常工作。
以下是IsFileLocked()
的代码。
Function IsFileLocked(sFile As String) As Boolean
On Error Resume Next
' \\ Open the file
Open sFile For Binary Access Read Write Lock Read Write As #1
' \\ Close the file
Close #1
' \\ If error occurs the document if open!
If Err.Number <> 0 Then
' \\ msgbox for demonstration purposes
'MsgBox Err.description, vbExclamation, "Warning File is opened"
'\\ Return true and clear error
IsFileLocked = True
Err.Clear
End If
End Function
有什么想法可以解决问题,或者有更好的方法打开文档?
根据您的描述,在某些情况下(并非总是如此),操作系统仍然允许成功打开文件,尽管该文件已在其他人的计算机中打开。
您对此无能为力。 代码中的逻辑似乎是正确的。
也许有一种解决方法:找出IsFileLocked()
在什么条件下报告错误结果。 是否仅在 文件首次保存或自动保存之前 ? 也许您可以通过要求所有同事将文档自动保存间隔设置为1分钟来找到解决方法,从而减少这种情况的发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.