[英]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.