如何确定一个文件是否被其他进程使用?

我想将数据保存到Excel单元格中,但是如果Excel文件是由其他进程打开的话会失败,那么在写入数据之前如何判断文件是否被其他进程使用?

谢谢,

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 

这里是function(由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 

来自Microsoft的参考: http : //support.microsoft.com/kb/209189

从Issun的回答中可以看出,如果你发现微软的FileLocked函数不起作用(例如,我发现它会错误地声称当前正在logging的WTV文件没有被locking),那么你可以使用这个方法这更残酷一些:

 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