2011-12-06 54 views

回答

2

MS對如何檢查是否可以訪問文件或者不是你嘗試使用他們編寫的名爲FileLocked函數打開它之前一個很好的例子。

Sub YourMacro() 
    Dim strFileName As String 
    ' Full path and name of file. 
    strFileName = "C:\test.doc" 
    ' Call function to test file lock. 
    If Not FileLocked(strFileName) Then 
     ' If the function returns False, open the document. 
     Documents.Open strFileName 
    End If 
End Sub 

這裏是功能(如寫MS):從微軟

Function FileLocked(strFileName As String) As Boolean 
    On Error Resume Next 
    ' If the file is already opened by another process, 
    ' and the specified type of access is not allowed, 
    ' the Open operation fails and an error occurs. 
    Open strFileName For Binary Access Read Write Lock Read Write As #1 
    Close #1 
    ' If an error occurs, the document is currently open. 
    If Err.Number <> 0 Then 
     ' Display the error number and description. 
     MsgBox "Error #" & Str(Err.Number) & " - " & Err.Description 
     FileLocked = True 
     Err.Clear 
    End If 
End Function 

參考:http://support.microsoft.com/kb/209189

+0

+1我已經多次部署這種技術來檢查共享網絡上的文件是否已被使用(儘管我唯一擔心的是該文件已經在Excel中打開) – brettdj

+0

謝謝你們。 – LianxiWang

+0

如果這個或其他答案有效,您可以通過選擇左上方的箭頭來「接受」它作爲答案。謝謝! – aevanko

0

Followingon從Issun的答案,如果你發現,微軟的FileLocked功能不工作(例如,我發現它會錯誤地聲稱當前正在錄製的WTV文件沒有被鎖定),那麼你可以使用這種方法,而不是更加殘忍:

Function FileLocked(sFilename) As Boolean 
    Dim oFile, sNewFile, iCount 
    If fso.FileExists(sFilename) = False Then 
     FileLocked = False 
     Exit Function 
    End If 
    ' Pick a random, unused, temp name 
    iCount = 0 
    Do 
     sNewFile = sFilename & ".tmp" & iCount 
     iCount = iCount + 1 
    Loop Until fso.FileExists(sNewFile) = False 
    ' Try to rename it to that. If it fails, then it is in use 
    On Error Resume Next 
    fso.MoveFile sFilename, sNewFile 
    If Err.Number = 0 Then 
     ' It moved okay, so rename it back 
     fso.MoveFile sNewFile, sFilename 
     FileLocked = False 
    Else 
     FileLocked = True 
    End If 
    On Error Goto 0  
End Function 
+0

謝謝你們。 – LianxiWang

相關問題