Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
814 views
in Technique[技术] by (71.8m points)

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

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 following error saying "object required"?:

Dim wbCopy As Excel.Workbook
Set wbCopy = wb.Sheets("Overview").Copy
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...