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

Categories

0 votes
898 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 Reply

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...