简体   繁体   English

如何将两张工作表复制到新工作簿?

[英]How to copy two sheets to a new workbook?

I have a workbook with many sheets.我有一个包含许多工作表的工作簿。 I'm trying to copy two sheets together to a new workbook.我正在尝试将两张纸一起复制到一个新的工作簿中。

I get我明白了

Run-time error 13 for type mismatch.类型不匹配的运行时错误 13。

Sub CopyBillStatandCosts()
    Dim MyBook As Workbook
    Dim NewBook As Workbook

    Set MyBook = ThisWorkbook
    Workbooks.Add ' Open a new workbook
    Set NewBook = ActiveWorkbook

    Set MyBook = ActiveWorkbook

    Sheets(11).Copy Before:=Workbooks(NewBook).Sheets(1)
    Sheets(9).Copy Before:=Workbooks(NewBook).Sheets(1)
    Workbooks(NewBook).Sheet1.Delete
End Sub

Update: I figured out the code.更新:我想出了代码。 But how do I refer to the sheets by their code names, which is best practice?但是,我如何通过代码名称来引用工作表,这是最佳实践? They are sheet9 and sheet 11.它们是 sheet9 和 sheet 11。

Sub copyBillStatandCosts()
    ThisWorkbook.Worksheets(Array("BillStat", "C")).Copy
End Sub

Your second你的第二个

Set MyBook = ActiveWorkbook

was probably meant to be可能本来就是

MyBook.Activate

although an overall simpler way to do this would be虽然这样做的整体更简单的方法是

Sub CopyBillStatandCosts()
    Sheets(Array("BillStat", "Costs")).Copy
End Sub

The Copy with no parameter makes the copy in a new workbook.不带参数的Copy在新工作簿中制作副本。

Copy Worksheets by Code Name in One Go在一个 Go 中按代码名称复制工作表

Sub copyBillStatandCosts()

    ThisWorkbook.Worksheets(Array(Sheet9.Name, Sheet11.Name)).Copy

    ' To continue to work with the new workbook, do the following:
    Dim NewBook As Workbook: Set NewBook = ActiveWorkbook
    ' e.g.:
    ' NewBook.SaveAs "C:\Test\Test.xlsx", xlOpenXMLWorkbook

    ' To continue to work with each new worksheet, do the following: 
    Dim bws As Worksheet: Set bws = NewBook.Worksheets(1)
    Dim cws As Worksheet: Set cws = NewBook.Worksheets(2)
    ' e.g.:
    MsgBox NewBook.Name & vbLf & bws.Name & vbLf & cws.Name

End Sub
  • Why use code names?为什么使用代号? Now you can rename the two worksheets in the tabs, and the code will still copy the right ones to a new workbook.现在您可以重命名选项卡中的两个工作表,代码仍会将正确的工作表复制到新工作簿。
  • Why in one go?为什么在一个 go 中? If there are references of the worksheets from one to each other they will still work in the new workbook ie will not refer to the worksheets in the source workbook.如果工作表相互引用,它们仍将在新工作簿中工作,即不会引用源工作簿中的工作表。

If you wanna use programmatic names, then just use Name property:如果您想使用编程名称,则只需使用Name属性:

ThisWorkbook.Sheets(Array(sheet9.Name, sheet11.Name)).Copy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM