【问题标题】:Save as xlsx then close with out closing all workbooks另存为 xlsx 然后关闭而不关闭所有工作簿
【发布时间】:2019-05-01 21:34:00
【问题描述】:

我想将活动工作簿另存为 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

【问题讨论】:

  • 我有点困惑。关闭ThisWorkbook 后,如果Excel.Workbooks.Count &gt; 0 要保持Excel 打开,但如果Excel.Workbooks.Count = 0 要关闭应用程序?
  • @FreeMan 我也是这样读的。似乎If Application.Workbooks.Count = 0 Then Application.Quit 可能是去这里的正确方式?
  • 可行,但我不得不将其更改为 If Application.Workbooks.Count = 1 Then Application.Quit

标签: excel vba


【解决方案1】:

如果您的代码正在关闭最后一个打开的工作簿,为了关闭 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

【讨论】:

  • 这是我想要的,但我不得不将它从 0 更改为 1 - If Excel.Application.Workbooks.Count = 1 Then
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多