Why does Worksheet.Copy not return a reference to the new workbook created

前端 未结 4 1470
遥遥无期
遥遥无期 2020-12-19 05:53

I have some code where wb is an existing multi-worksheet workbook. If I copy one of the sheets \"Overview\" a new workbook is created - so why does the followin

4条回答
  •  悲哀的现实
    2020-12-19 05:57

    The Worksheet.Copy method doesn't return a reference to the new Workbook. You might use a Worksheet reference instead:

    Dim wsCopy As Excel.Worksheet    'changed from wb to wsCopy
    

    As you know, if you don't supply either the After or Before argument it copies to a new Workbook. Copying within the same workbook would use this code:

    Set wsCopy = wb.Worksheets("Overview")
    wsCopy.Copy After:= wb.Worksheets(1)    'or Before:=
    

    If you want to copy the sheet to a new workbook, and retain a reference to it, then this needs to be done in stages:

    Dim wbNew As Excel.Workbook
    Dim wsCopied As Excel.Worksheet
    
    Set wbNew = Workbooks.Add
    wsCopy.Copy before:=wbNew.Worksheets(1)
    Set wsCopied = wbNew.Worksheets(1)
    

    If you only need to keep a reference to the new workbook then just omit the last line (and the variable declaration for wsCopied).

提交回复
热议问题