另存为xlsx,然后关闭,关闭所有工作簿

时间:2019-05-01 12:16:09

标签: excel vba

我想将活动工作簿另存为xlsx,然后关闭它而不关闭所有打开的excel工作簿。该代码有效,但是关闭所有打开的excel文件。

如果我删除Application.Quit并保留ThisWorkbook.Close,则只有在我打开一本以上的工作簿时,它才能工作,但是如果我只打开一本工作簿,则它会关闭,但将保留空白的excel窗口。

Sub SaveAsXlsx()

Dim varResponse As Variant
varResponse = MsgBox("Save As xlsx Removing Macros & Then Closes The Workbook", vbYesNo, "Save As xlsx")
If varResponse <> vbYes Then Exit Sub

Application.DisplayAlerts = False
Dim FilePath As String
FilePath = ThisWorkbook.FullName
FilePath = Left(FilePath, Len(FilePath) - 5) & " To Review" & ".xlsx"

ThisWorkbook.SaveAs Filename:=FilePath, FileFormat:= _
    xlOpenXMLWorkbook, CreateBackup:=False

'Enter Anything to Happen on xlsx Book Here
Range("A1").Select


ThisWorkbook.Save

FilePath = Application.ActiveWorkbook.FullName
MsgBox "Saved Review Copy As" & Chr(10) & Chr(10) & FilePath, , "Saved!"

Application.Quit
ThisWorkbook.Close


End Sub

1 个答案:

答案 0 :(得分:0)

如果代码正在关闭上一个打开的工作簿,则要关闭 Excel,但是如果还有其他工作簿在打开,则请保持打开状态,您需要检查Application.Workbook.Count属性,像这样:

Sub SaveAsXlsx()

  Dim varResponse As Variant
  varResponse = MsgBox("Save As xlsx Removing Macros & Then Closes The Workbook", vbYesNo, "Save As xlsx")
  If varResponse <> vbYes Then Exit Sub

  Application.DisplayAlerts = False
  Dim FilePath As String
  FilePath = ThisWorkbook.FullName
  FilePath = Left(FilePath, Len(FilePath) - 5) & " To Review" & ".xlsx"

  ThisWorkbook.SaveAs Filename:=FilePath, FileFormat:= _
                      xlOpenXMLWorkbook, CreateBackup:=False

'Enter Anything to Happen on xlsx Book Here
  Range("A1").Select


  ThisWorkbook.Save

  FilePath = Application.ActiveWorkbook.FullName
  MsgBox "Saved Review Copy As" & Chr(10) & Chr(10) & FilePath, , "Saved!"

  ThisWorkbook.Close

  If Excel.Application.Workbooks.Count = 0 Then
    Application.Quit
  End If

End Sub