转换以下函数是否容易,而不只是0或1,它给出了以下三个输出:
0 - 表示文件已关闭 1 - 表示文件已经打开 2 - 表示文件不存在
这是功能
Function IsFileReadOnlyOpen(FileName As String)
Dim iFilenum As Long
Dim iErr As Long
On Error Resume Next
iFilenum = FreeFile()
Open FileName For Input Lock Read As #iFilenum
Close iFilenum
iErr = Err
On Error GoTo 0
Select Case iErr
Case 0: IsFileReadOnlyOpen = 0
Case 70: IsFileReadOnlyOpen = 1
Case Else: Error iErr
End Select
End Function
答案 0 :(得分:2)
您可以在功能开头添加:
If Dir(FileName) = "" Then 'File does not exist
IsFileReadOnlyOpen = 2
Exit Function 'Or not - I don't know if you want to create the file or exit in that case.
End If
我同意你应该使用枚举来更容易理解的评论。
PS:正如Martin Milan所评论,这可能会导致问题。或者,您可以使用:
With New FileSystemObject
If .FileExists(FileName) Then
IsFileReadOnlyOpen = 2
Exit Function 'Or not - I don't know if you want to create the file or exit in that case.
End If
End With
答案 1 :(得分:1)
如果这是您的难度,您可以使用FileSystemObject显式测试文件是否存在。
为了做到这一点,您需要添加对Microsoft Scripting Runtime库的引用,我倾向于避免这种情况。
您可以使用Win32API中的FindFirstFile对此进行测试,但这样做更为复杂 - 如果用户实际在Mac上运行,也无法帮助您...
答案 2 :(得分:0)
结束了:
Enum FileOpenState
ExistsAndClosed = 0
ExistsAndOpen = 1
NotExists = 2
End Enum
Function IsFileReadOnlyOpen(FileName As String)
With New FileSystemObject
If Not .FileExists(FileName) Then
IsFileReadOnlyOpen = 2 ' NotExists = 2
Exit Function 'Or not - I don't know if you want to create the file or exit in that case.
End If
End With
Dim iFilenum As Long
Dim iErr As Long
On Error Resume Next
iFilenum = FreeFile()
Open FileName For Input Lock Read As #iFilenum
Close iFilenum
iErr = Err
On Error GoTo 0
Select Case iErr
Case 0: IsFileReadOnlyOpen = 0
Case 70: IsFileReadOnlyOpen = 1
Case Else: IsFileReadOnlyOpen = 1 'Error iErr
End Select
End Function