简体   繁体   English

检查csv文件是否从vba打开

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

I want to export table in access to csv file.我想导出表以访问 csv 文件。 It works fine if the csv file where I want to export the table is closed.如果我想导出表的 csv 文件关闭,它工作正常。 But if the file is open, I get no error and neither the table is exported.但是如果文件是打开的,我不会出错,也不会导出表。 Is there any way to check if the csv file is open already and if possible to close it??有没有办法检查 csv 文件是否已经打开,如果可以关闭它?

Found the solution here.在这里找到了解决方案。 VBA Function to Check Whether File or Document Is Open https://support.microsoft.com/en-us/kb/209189用于检查文件或文档是否打开的 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

As reported in this microsoft support page , you can check if a file is read-only:如此 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

If you opened that file, you could always close any file you open.如果您打开该文件,您可以随时关闭您打开的任何文件。

intFile = FreeFile()
Open "c:\example.csv" For Output As #intFile
Write #intFile
Close #intFile

If you don't specify the file name in the Close statement, you will close all the files that you opened.如果您没有在Close语句中指定文件名,您将关闭您打开的所有文件。

If the file is opened by another application, I don't know if there is a way to close it.如果文件被另一个应用程序打开,我不知道是否有办法关闭它。

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

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