VBA关闭空白工作簿

时间:2015-11-30 19:58:06

标签: excel vba excel-vba

之前我发现了这个问题,但是从未回答过。我有一些VBA代码格式化不同的文件,并将它们输出到Excel电子表格,然后将副本保存到两个不同的目录。但是,我遇到的麻烦是它打开了一个空的工作簿,我不知道如何关闭它。我尝试过Workbooks.Close和Application.Quit,但都没有用。任何帮助将不胜感激。以下是我所指的代码部分:

sSaveAsFilePath = "\\Filesrv02\test\remit" + ".csv"
sSaveAsFilePath2 = "\\Filesrv02\backup\remit" + Format(Date, "mmddyy") + ".csv"

Application.DisplayAlerts = False
ChDir "\\Filesrv02\test"
ActiveWorkbook.SaveAs FileName:=sSaveAsFilePath, _
       FileFormat:=xlCSV, CreateBackup:=False
      'ActiveWorkbook.Close False

ChDir "\\Filesrv02\Backup"
       ActiveWorkbook.SaveAs FileName:=sSaveAsFilePath2, _
       FileFormat:=xlCSV, CreateBackup:=False
       ActiveWorkbook.Close True
Application.DisplayAlerts = False
MsgBox ("done")

End Sub

2 个答案:

答案 0 :(得分:1)

由于您只是从工作簿中复制工作表以保存在不同位置,因此您只需将该工作表复制出工作簿并将其保存到其他位置即可。这将使原始工作簿保持完整,并且不会制作神秘的空白工作簿。另外,请注意我如何使用变量限定所有工作簿和工作表。

sSaveAsFilePath = "\\Filesrv02\test\remit" + ".csv"
sSaveAsFilePath2 = "\\Filesrv02\backup\remit" + Format(Date, "mmddyy") + ".csv"

Application.DisplayAlerts = False

Dim wb As Workbook, wbC As Workbook, ws As Worksheet

Set wb = ThisWorkbook
Set ws = ws.Sheets("mySheet") 'change name as needed

'create and save test version
ws.Copy

Set wbC = ActiveWorkbook

With wbC
    .SaveAs Filename:=sSaveAsFilePath, FileFormat:=xlCSV, CreateBackup:=False
    .Close
End With

'create and save backup version
ws.Copy

Set wbC = ActiveWorkbook

With wbC
    .SaveAs Filename:=sSaveAsFilePath2, FileFormat:=xlCSV, CreateBackup:=False
    .Close
End With

Application.DisplayAlerts = False

MsgBox ("done")

答案 1 :(得分:0)

保存前创建新工作簿

    Application.Workbooks.Add
    ActiveWorkbook.SaveAs FileName:=sSaveAsFilePath, _
           FileFormat:=xlCSV, CreateBackup:=False
    ActiveWorkbook.Close False