检查 csv 文件是否从 vba 打开
to check if csv file is open from vba
我想导出 table 以访问 csv 文件。如果我要导出 table 的 csv 文件关闭,它工作正常。但是如果文件是打开的,我不会收到任何错误,也不会导出 table。
有什么方法可以检查 csv 文件是否已经打开,如果可能的话关闭它??
如 this microsoft support page 中所述,您可以检查文件是否为只读:
Sub Example1()
' Test to see if the Read-only attribute was assigned to the file.
If GetAttr("c:\example.csv") And vbReadOnly Then
MsgBox "File is Read-only"
Else
MsgBox "File is not read-only"
End If
End Sub
如果您打开了该文件,您可以随时关闭打开的任何文件。
intFile = FreeFile()
Open "c:\example.csv" For Output As #intFile
Write #intFile
Close #intFile
如果您在Close
语句中没有指定文件名,您将关闭您打开的所有文件。
如果文件被其他应用打开,不知道有没有办法关闭
在这里找到了解决方案。
VBA检查文件或文档是否打开的函数https://support.microsoft.com/en-us/kb/209189
Sub MacroName()
Dim Path As String
Path = "C:\test.doc"
If Not FileLocked(Path) Then
Documents.Open strFileName
End If
End Sub
Function FileLocked(Path As String) As Boolean
On Error Resume Next
Open strFileName For Binary Access Read Write Lock Read Write As #1
Close #1
If Err.Number <> 0 Then
MsgBox "Error #" & Str(Err.Number) & " - " & Err.Description
FileLocked = True
Err.Clear
End If
End Function
我想导出 table 以访问 csv 文件。如果我要导出 table 的 csv 文件关闭,它工作正常。但是如果文件是打开的,我不会收到任何错误,也不会导出 table。 有什么方法可以检查 csv 文件是否已经打开,如果可能的话关闭它??
如 this microsoft support page 中所述,您可以检查文件是否为只读:
Sub Example1()
' Test to see if the Read-only attribute was assigned to the file.
If GetAttr("c:\example.csv") And vbReadOnly Then
MsgBox "File is Read-only"
Else
MsgBox "File is not read-only"
End If
End Sub
如果您打开了该文件,您可以随时关闭打开的任何文件。
intFile = FreeFile()
Open "c:\example.csv" For Output As #intFile
Write #intFile
Close #intFile
如果您在Close
语句中没有指定文件名,您将关闭您打开的所有文件。
如果文件被其他应用打开,不知道有没有办法关闭
在这里找到了解决方案。 VBA检查文件或文档是否打开的函数https://support.microsoft.com/en-us/kb/209189
Sub MacroName()
Dim Path As String
Path = "C:\test.doc"
If Not FileLocked(Path) Then
Documents.Open strFileName
End If
End Sub
Function FileLocked(Path As String) As Boolean
On Error Resume Next
Open strFileName For Binary Access Read Write Lock Read Write As #1
Close #1
If Err.Number <> 0 Then
MsgBox "Error #" & Str(Err.Number) & " - " & Err.Description
FileLocked = True
Err.Clear
End If
End Function