0

转换以下函数是否容易,以便它提供以下三个输出而不是 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
4

3 回答 3

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

我同意您应该使用 enum 以使其更易于理解的评论。

PS:正如马丁米兰所说,可能会导致问题。或者,您可以使用这个:

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
于 2012-05-04T15:35:30.590 回答
1

如果这是您的困难,您可以使用 FileSystemObject 显式测试文件是否存在。

为了做到这一点,您需要添加对 Microsoft Scripting Runtime 库的引用,我倾向于避免这种情况。

您可以使用 Win32API 中的 FindFirstFile 进行测试,但这涉及更多一点 - 如果用户实际上在 Mac 上运行,也不会帮助您...

于 2012-05-04T15:42:09.037 回答
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
于 2012-05-09T15:51:48.660 回答