在宏中使用Excel VBA关闭活动工作簿

时间:2017-02-16 21:04:54

标签: excel-vba vba excel

我在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

任何帮助将不胜感激。提前谢谢。

1 个答案:

答案 0 :(得分:0)

好吧,但是你特意要求Excel关闭工作簿,而不是Object Excel应用程序本身。尝试替换此行

ThisWorkbook.Close False

有了这个:

Application.Quit

也就是说,假设两者都在同一个Excel实例上运行,就好像它一样。