转换函数以给第三个状态

将下面的函数转换成简单的方式,而不仅仅是0或1,它会给出以下三个输出:

0 – 表示文件closures1 – 表示文件已经打开2 – 表示文件不存在

这是function

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 

你可以在你的函数的开头添加这个:

 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:正如马丁米兰评论,这可能会导致问题。 或者,你可以使用这个:

 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 

如果这是你的困难,你可以使用FileSystemObject来显式testing文件的存在。

您需要添加一个对Microsoft脚本运行时库的引用,但为了做到这一点,我倾向于尝试避免这种情况。

您可以使用Win32API中的FindFirstFile来testing这个,但是这会涉及更多一点 – 如果用户实际上在Mac上运行,也不会对您有所帮助。

已经结束了:

 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