简体   繁体   中英

VBA close blank workbook

I found this question asked before, but it was never answered. I have some VBA code that formats different files and outputs them onto an Excel spreadsheet, and then saves copies to two different directories. However, the trouble I'm having is that it leaves an empty workbook open and I don't know how to close it. I have tried Workbooks.Close, and Application.Quit but neither worked. Any help would be greatly appreciated. Here is the part of my code that I'm referring to:

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

Since you are only copying a sheet out of your workbook to save in different locations, you can just copy that sheet out of the workbook and save it to another location. This will leave your original workbook intact, and will not make a mysterious blank workbooks. Also, note how I qualified all the workbooks and worksheets with variables.

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")

Create a new workbook before save

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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