检查文件是否处于只读状态(if语句)VBA
总之,我有下面的代码,我需要检查第一个可用的文件,它不是只读状态,并使用文件名作为更大模块的一部分 例如,如果其他用户正在使用Transactions1.csv,则检查Transactions2是否正在使用等 我遇到的问题是,它似乎总是使用Transactions3.csv,而忽略文件1、2和4。(即使它们不处于只读状态)。任何帮助都将不胜感激检查文件是否处于只读状态(if语句)VBA,vba,excel,if-statement,readonly,Vba,Excel,If Statement,Readonly,总之,我有下面的代码,我需要检查第一个可用的文件,它不是只读状态,并使用文件名作为更大模块的一部分 例如,如果其他用户正在使用Transactions1.csv,则检查Transactions2是否正在使用等 我遇到的问题是,它似乎总是使用Transactions3.csv,而忽略文件1、2和4。(即使它们不处于只读状态)。任何帮助都将不胜感激 Sub CheckIFFileisopen() 'checking multiple files PMFTransFile = "\\Csdatg0
Sub CheckIFFileisopen()
'checking multiple files
PMFTransFile = "\\Csdatg04\psproject\Robot\Project Preload\Transactions\Transactions1.csv"
Set TransworkBook = Workbooks.Open(PMFTransFile)
'Check to see if file is already open
If TransworkBook.ReadOnly Then
ActiveWorkbook.Close
'check if 2nd file is available
PMFTransFile = "\\Csdatg04\psproject\Robot\Project Preload\Transactions\Transactions2.csv"
Set TransworkBook = Workbooks.Open(PMFTransFile)
If TransworkBook.ReadOnly Then
ActiveWorkbook.Close
'check if 3rd file is available
PMFTransFile = "\\Csdatg04\psproject\Robot\Project Preload\Transactions\Transactions3.csv"
Set TransworkBook = Workbooks.Open(PMFTransFile)
If TransworkBook.ReadOnly Then
ActiveWorkbook.Close
'check if 4th file is available
PMFTransFile = "\\Csdatg04\psproject\Robot\Project Preload\Transactions\Transactions4.csv"
Set TransworkBook = Workbooks.Open(PMFTransFile)
MsgBox "Cannot update Transactions, someone currently using file. Please try again in a few minutes."
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End
Exit Sub
End If
End If
End If
End Sub
因为您有相同的路径和相似的文件名,所以我们可以使用循环来检查文件的状态。此外,您可能希望看到有关如何检查文件是否打开的链接
Sub Sample()
Dim sPath As String, SFile As String
Dim i As Long
Dim Ret As Variant
sPath = "\\Csdatg04\psproject\Robot\Project Preload\Transactions\Transactions"
For i = 1 To 4
SFile = sPath & i & ".csv"
Ret = IsWorkBookOpen(SFile)
If Ret = True Then
MsgBox SFile & " is open. Will now check for next File"
Else
MsgBox SFile & " is Closed. We will work with this file"
Exit For
End If
Next i
End Sub
Function IsWorkBookOpen(FileName As String)
Dim ff As Long, ErrNo As Long
On Error Resume Next
ff = FreeFile()
Open FileName For Input Lock Read As #ff
Close ff
ErrNo = Err
On Error GoTo 0
Select Case ErrNo
Case 0: IsWorkBookOpen = False
Case 70: IsWorkBookOpen = True
Case Else: Error ErrNo
End Select
End Function