在工作表后保存。不使用ActiveWorkbook进行复制

时间:2018-09-14 13:19:37

标签: excel vba excel-vba

我不喜欢使用ActiveWorkbook。是否可以在不坚持使用ActiveWorkbook的情况下不使用Sheets.Copy来重写以下代码

Sub test()
ThisWorkbook.Sheets(Array("Lists", "Input", "ListsPars")).Copy
ActiveWorkbook.SaveAs "Palim.xlsx"
ActiveWorkbook.Close
End Sub

1 个答案:

答案 0 :(得分:2)

Sub test()
    With Workbooks.Add ' add a new workbook and reference it
        ThisWorkbook.Sheets(Array("Lists", "Input", "ListsPars")).Copy after:=.Worksheets(1) ' copy wanted sheets from 'ThisWorkbook' after reference workbook first sheet
        Application.DisplayAlerts = False ' prevent alert coming form subsequent sheet deletion statament
        .Worksheets(1).Delete ' delete referenced workbook first sheet
        Application.DisplayAlerts = True 'restore alerts back on
        .SaveAs "Palim.xlsx" ' save referenced workbook
        .Close ' close referenced workbook
    End With
End Sub