How to copy sheets to another workbook using vba?

后端 未结 10 1907
故里飘歌
故里飘歌 2020-11-27 17:52

So, what I want to do, generally, is make a copy of a workbook. However, the source workbook is running my macros, and I want it to make an identical copy of itself, but wit

10条回答
  •  天命终不由人
    2020-11-27 18:15

    I would like to slightly rewrite keytarhero's response:

    Sub CopyWorkbook()
    
    Dim sh as Worksheet,  wb as workbook
    
    Set wb = workbooks("Target workbook")
    For Each sh in workbooks("source workbook").Worksheets
       sh.Copy After:=wb.Sheets(wb.sheets.count) 
    Next sh
    
    End Sub
    

    Edit: You can also build an array of sheet names and copy that at once.

    Workbooks("source workbook").Worksheets(Array("sheet1","sheet2")).Copy _
             After:=wb.Sheets(wb.sheets.count)
    

    Note: copying a sheet from an XLS? to an XLS will result into an error. The opposite works fine (XLS to XLSX)

提交回复
热议问题