我需要检查文件是否已经打开以加快我的代码速度。目前,它循环遍历列表,打开一个带有路径的文件,文件名来自列表,有几行代码,这意味着我想要打开的文件是否在此路径中的文件夹中,它仍然可以这样做:
If Not IsFileOpen("G:\BS\Josh Whitfield\1. Work work\Credit_Chasing\NEW PROCESS\" & file) Then
If filevar <> "" Then
Workbooks.Open "G:\BS\Josh Whitfield\1. Work work\Credit_Chasing\NEW PROCESS\" & file
Else
Workbooks.Open "G:\BS\Josh Whitfield\1. Work work\Credit_Chasing\NEW PROCESS\" & Range("F" & i).Value & "\" & file
End If
End If
我还有一个函数可以检测文件是否已经打开,但我想要更好的一个或一些帮助让当前的文件与子文件夹一起使用:
Function IsFileOpen(filename As String)
Dim filenum As Integer, errnum As Integer
On Error Resume Next ' Turn error checking off.
filenum = FreeFile() ' Get a free file number.
' Attempt to open the file and lock it.
Open filename For Input Lock Read As #filenum
Close filenum ' Close the file.
errnum = Err ' Save the error number that occurred.
On Error GoTo 0 ' Turn error checking back on.
' Check to see which error occurred.
Select Case errnum
' No error occurred.
' File is NOT already open by another user.
Case 0
IsFileOpen = False
' Error number for "Permission Denied."
' File is already opened by another user.
Case 70
IsFileOpen = True
' Another error occurred.
Case Else
Error errnum
End Select
End Function
感谢您的帮助!
答案 0 :(得分:0)
管理以使用不同的功能解决它:
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
subCheck = False
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
IsWorkBookOpen = ""
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: IsWorkBookOpen = ""
End Select
End Function
和sub的设置:
ret = IsWorkBookOpen("G:\BS\Josh Whitfield\1. Work work\Credit_Chasing\NEW PROCESS\" & file)
retSub = subCheck
If ret <> True Then
If ret = False Then
Workbooks.Open "G:\BS\Josh Whitfield\1. Work work\Credit_Chasing\NEW PROCESS\" & file
ElseIf ret = "" Then
'subCheck = True
Workbooks.Open "G:\BS\Josh Whitfield\1. Work work\Credit_Chasing\NEW PROCESS\" & Range("F" & i).Value & "\" & file
End If
End If
如果你想查看文件是否打开,这个代码对每个人都有用,它可以用于我的目的,因为我不介意打开3种类型的文件,这不是一个完全可靠的方法。