0

次の関数を変換して、0または1だけでなく、次の3つの出力が得られるようにするのは簡単でしょうか。

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

理解しやすくするために列挙型を使用する必要があるというコメントに同意します。

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
于 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 に答える