进程完成后,Excel宏不会关闭CSV文件

时间:2013-02-13 20:57:48

标签: excel excel-vba vba

我正在运行以下脚本,它似乎没有关闭,脚本运行时的文件。如何编辑脚本以便它可以关闭脚本。

Sub LoopFiles()

    Dim MyFileName As String, MyPath As String

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    MyPath = "C:\macro\"

    MyFileName = Dir(MyPath & "*.xlsx")

    ChDir "C:\macro\csv"

    Do Until MyFileName = ""
        Workbooks.Open Filename:=MyPath & MyFileName
        ActiveWorkbook.SaveAs Filename:=Left(MyFileName, InStr(1, MyFileName, ".xlsx") - 1), FileFormat:=xlCSV, CreateBackup:=False
        MyFileName = Dir
    Loop

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True

End Sub

1 个答案:

答案 0 :(得分:2)

添加以下行:ActiveWorkbook.Close False

在我在下面演示的空间中。

Do Until MyFileName = ""
        Workbooks.Open Filename:=MyPath & MyFileName
        ActiveWorkbook.SaveAs Filename:=Left(MyFileName, InStr(1, MyFileName, ".xlsx") - 1), FileFormat:=xlCSV, CreateBackup:=False
        ActiveWorkbook.Close False
        MyFileName = Dir
Loop

或更清洁的版本执行此操作:

Dim wkb as Workbook

Do Until MyFileName = ""
   Set wkb = Workbooks.Open(Filename:=MyPath & MyFileName)
   With wkb
       .SaveAs Filename:=Left(MyFileName, InStr(1, MyFileName, ".xlsx") - 1), FileFormat:=xlCSV, CreateBackup:=False
       .Close False
   End With
Loop