在excel退出时忽略"你想保存"框吗?

Cas*_*thy 6 vbscript excel vba excel-vba

我有一个脚本打开excel文件并运行宏,然后退出该文件.由于文件处于只读模式,并且脚本对文件进行临时更改,因此当脚本调用myExcelWorker.Quit()excel询问我是否要保存更改时,必须单击"否".有没有办法退出程序并跳过此框?

' Create a WshShell to get the current directory
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")

' Create an Excel instance
Dim myExcelWorker
Set myExcelWorker = CreateObject("Excel.Application") 

myExcelWorker.Visible = True

' Tell Excel what the current working directory is 
' (otherwise it can't find the files)
Dim strSaveDefaultPath
Dim strPath
strSaveDefaultPath = myExcelWorker.DefaultFilePath
strPath = WshShell.CurrentDirectory
myExcelWorker.DefaultFilePath = strPath

' Open the Workbook specified on the command-line 
Dim oWorkBook
Dim strWorkerWB
strWorkerWB = strPath & "\BugHistogram_v2.xlsm"

Set oWorkBook = myExcelWorker.Workbooks.Open(strWorkerWB)

' Build the macro name with the full path to the workbook
Dim strMacroName
strMacroName = "CreateImagesButton_Click"
on error resume next 
   ' Run the calculation macro
   myExcelWorker.Run strMacroName
   if err.number <> 0 Then
      ' Error occurred - just close it down.
   End If
   err.clear
on error goto 0 

' oWorkBook.Save ' this is ignored because it's read only 

myExcelWorker.DefaultFilePath = strSaveDefaultPath

' Clean up and shut down
Set oWorkBook = Nothing

' Don’t Quit() Excel if there are other Excel instances 
' running, Quit() will 
' shut those down also
if myExcelWorker.Workbooks.Count = 0 Then
   myExcelWorker.Quit
End If

myExcelWorker.Quit()

Set myExcelWorker = Nothing
Set WshShell = Nothing
Run Code Online (Sandbox Code Playgroud)

Isa*_*vaa 7

ActiveWorkbook.Close False (关闭工作簿)

Application.Quit (退出Excel - 不提示保存更改)

从Microsoft支持的如何在Excel中关闭工作簿时禁止"保存更改"提示:

若要在不保存任何更改的情况下强制关闭工作簿,请在该工作簿的Visual Basic模块中键入以下代码:

Sub Auto_Close()
    ThisWorkbook.Saved = True
End Sub
Run Code Online (Sandbox Code Playgroud)

由于Saved属性设置为True,因此Excel会像保存工作簿一样进行响应,并且自上次保存以来未发生任何更改.

程序的DisplayAlerts属性可用于相同的目的.例如,以下宏关闭DisplayAlerts,关闭活动工作簿而不保存更改,然后再次打开 DisplayAlerts.

Sub CloseBook()
    Application.DisplayAlerts = False
    ActiveWorkbook.Close
    Application.DisplayAlerts = True
End Sub
Run Code Online (Sandbox Code Playgroud)

您还可以使用Close方法的SaveChanges参数.

以下宏关闭工作簿而不保存更改:

Sub CloseBook2()
    ActiveWorkbook.Close savechanges:=False
End Sub
Run Code Online (Sandbox Code Playgroud)