在宏中使用 Excel VBA 关闭活动工作簿
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42284586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Excel VBA in a Macro to Close Active Workbook
提问by johnveit
I'm using VBA in an Excel Macro that copies data from the active workbook to a second workbook, closes the second workbook and then closes the first workbook. The problem is the ActiveWorkbook.close false only closes the worksheets and not the workbook; Excel is still running. The two sections of code were tested separately and work fine; when put together in the macro the closing first workbook problem exits. My code is:
我在 Excel 宏中使用 VBA,该宏将数据从活动工作簿复制到第二个工作簿,关闭第二个工作簿,然后关闭第一个工作簿。问题是 ActiveWorkbook.close false 只关闭工作表而不是工作簿;Excel 仍在运行。两段代码分别测试,运行良好;当放在宏中时,关闭的第一个工作簿问题就会退出。我的代码是:
Sub SacoFieldUnitDataCopy()
' SacoFieldUnitsDataCopy Macro
' This macro copies the Saco Field Units Avail_Run Stat sheet to a new workbook.
'
ActiveWorkbook.RefreshAll
Call ConvertToValues("Saco Field Units Avail_Run Stat")
Sheets("Saco Field Units Avail_Run Stat").Select
Sheets("Saco Field Units Avail_Run Stat").Copy
ChDir "C:\Saco Units Avail_Run Stats"
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:= _
"C:\Saco Units Avail_Run Stats\Saco Unit Avail_Run Data" & " " & VBA.Format(Date, "MM-DD-YYYY") & ".xlsx", FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False
Call CloseAllOtherWorkbooks
Application.Wait (Now + TimeValue("0:00:03"))
ThisWorkbook.Close False
Application.DisplayAlerts = True
End Sub
Function ConvertToValues(Sheetname As String)
'Select Sheet
Sheets(Sheetname).Select
'Select All Cells
Range("B4:C26").Select
Selection.Copy
'Paste Special to remove formulas
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
'Put cursor back on cell a1
Range("a1").Select
End Function
Function CloseAllOtherWorkbooks()
Dim WBs As Workbook
For Each WBs In Application.Workbooks
If Not WBs.Name = ThisWorkbook.Name Then WBs.Close False
Next WBs
End Function
Any help would be appreciated. thanks in advance.
任何帮助,将不胜感激。提前致谢。
回答by fabio.avigo
Well, but you are specifically asking Excel to close the Workbook, not the Object Excel Application per se. Try replacing this line
好吧,但您特别要求 Excel 关闭工作簿,而不是对象 Excel 应用程序本身。尝试更换这一行
ThisWorkbook.Close False
With this:
有了这个:
Application.Quit
That is, assuming both are running on the same instance of Excel, which seems like it.
也就是说,假设两者都在同一个 Excel 实例上运行,这看起来是这样。