繁体   English   中英

检查csv文件是否从vba打开

[英]to check if csv file is open from vba

我想导出表以访问 csv 文件。 如果我想导出表的 csv 文件关闭,它工作正常。 但是如果文件是打开的,我不会出错,也不会导出表。 有没有办法检查 csv 文件是否已经打开,如果可以关闭它?

在这里找到了解决方案。 用于检查文件或文档是否打开的 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

如此 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语句中指定文件名,您将关闭您打开的所有文件。

如果文件被另一个应用程序打开,我不知道是否有办法关闭它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM