简体   繁体   English

将工作表复制到新工作簿中

[英]Copy a Worksheet into a new Workbook

I get a runtime error with ws.copy -> without the code works but just creates an empty workbook.我在 ws.copy 中遇到运行时错误 -> 没有代码有效,但只是创建了一个空工作簿。

Sub SaveWorksheetAsXlsx(ws As Worksheet)
Dim filePath As String
filePath = ThisWorkbook.Path & "\" & ws.Name & ".xlsx"

' Create a new workbook
Dim newWorkbook As Workbook
Set newWorkbook = Workbooks.Add

' Copy the worksheet to the new workbook
ws.Copy 'After:=newWorkbook.Worksheets(1)

' Save the new workbook
newWorkbook.SaveAs filePath, FileFormat:=xlOpenXMLWorkbook
newWorkbook.Close SaveChanges:=False
End Sub

set newWorkbook = workbooks.Add creates a new workbook. set newWorkbook = workbooks.Add创建一个新工作簿。 But ws.Copy without arguments copies ws to a new workbook.但是没有参数的ws.Copyws复制到一个新的工作簿。 Now you have two new workbooks which is clearly not what you intend.现在你有两个新的工作簿,这显然不是你想要的。 MS learning documents gives an example of how to do copy a worksheet in its documentation on the copy command. MS 学习文档在其关于复制命令的文档中给出了如何复制工作表的示例。 Reference: https://learn.microsoft.com/en-us/office/vba/api/excel.worksheet.copy参考: https ://learn.microsoft.com/en-us/office/vba/api/excel.worksheet.copy

Sub foo()
    Call SaveWorksheetAsXlsx(Worksheets("Sheet3"))
End Sub

Sub SaveWorksheetAsXlsx(ws As Worksheet)
Dim filePath As String

    filePath = ThisWorkbook.Path & "\" & ws.Name & ".xlsx"
    If Not CreateObject("Scripting.FileSystemObject").FileExists(filePath) Then
        ws.Copy
        ActiveWorkbook.SaveAs filePath, FileFormat:=xlOpenXMLWorkbook
        ActiveWorkbook.Close SaveChanges:=False
    Else
        MsgBox "Error: unable to save file. File already exists: " + filePath
    End If
    
 End Sub

This obviously relies on the expected behavior that when you copy a worksheet to a new workbook that workbook becomes the active workbook.这显然依赖于当您将工作表复制到新工作簿时该工作簿成为活动工作簿的预期行为。 I have used this before without any problems (for many years I guess), although it does make me a little nervous relying on default behaviors.我以前用过这个没有任何问题(我想很多年了),尽管依赖默认行为确实让我有点紧张。 So you may consider adding some guard clauses, perhaps only saving the workbook if it has an empty path (ie, ensure it is a newly added workbook -> if ActiveWorkbook.Path = "" . So, coding prophylacticly and very cautiously:因此,您可以考虑添加一些保护子句,也许只在工作簿的路径为空时才保存工作簿(即,确保它是新添加的工作簿 -> if ActiveWorkbook.Path = "" 。因此,预防性和非常谨慎地编码:

Sub foo()
    Call SaveWorksheetAsXlsx(Worksheets("Sheet3"))
End Sub

Sub SaveWorksheetAsXlsx(ws As Worksheet)
Dim filePath As String

    filePath = ThisWorkbook.Path & "\" & ws.Name & ".xlsx"
    If Not CreateObject("Scripting.FileSystemObject").FileExists(filePath) Then
        ws.Copy
        If ActiveWorkbook.Path = "" Then 'Extra check to ensure this is a newly created and unsaved workbook
            ActiveWorkbook.SaveAs filePath, FileFormat:=xlOpenXMLWorkbook
            ActiveWorkbook.Close SaveChanges:=False
        Else
            MsgBox "Unexpected error attempting to save file " + filePath
        End If
    Else
        MsgBox "Error: unable to save file. File already exists: " + filePath
    End If
    
 End Sub

Copy Sheet to a New Workbook将工作表复制到新工作簿

  • If you replace As Worksheet with As Object , the procedure will also work for charts.如果将As Worksheet替换为As Object ,该过程也适用于图表。
  • To reference the last opened workbook, you can safely use Workbook(Workbooks.Count) .要引用上次打开的工作簿,您可以安全地使用Workbook(Workbooks.Count)
  • Turn off Application.DisplayAlerts to overwrite without confirmation.关闭Application.DisplayAlerts以在不确认的情况下覆盖。 If you don't do this, when the file exists, you'll be asked to save it.如果您不这样做,当文件存在时,系统会要求您保存它。 If you select No or Cancel , the following error will occur:如果您选择NoCancel ,将出现以下错误:
    Run-time error '1004': Method 'SaveAs' of object '_Workbook' failed运行时错误“1004”:对象“_Workbook”的方法“SaveAs”失败
  • If your intent is to reference the sheet's workbook, you can use the .Parent property.如果您的目的是引用工作表的工作簿,则可以使用.Parent属性。 Then the procedure will not be restricted just to the workbook containing this code ( ThisWorkbook ).然后该过程将不仅限于包含此代码的工作簿 ( ThisWorkbook )。 Otherwise, replace Sheet.Parent with ThisWorkbook .否则,将Sheet.Parent替换为ThisWorkbook
  • If you instead of the backslash ( \ ) use Application.PathSeparator , the procedure will also work on computers with a different operating system than Windows .如果您使用Application.PathSeparator而不是反斜杠 ( \ ),则该过程也适用于操作系统与Windows不同的计算机。
  • For a new workbook, the default type is .xlsx so you don't need to specify the file extension or format.对于新工作簿,默认类型为.xlsx ,因此您无需指定文件扩展名或格式。
Sub SaveSheetAsXlsx(ByVal Sheet As Object)
    ' Copy the sheet to a new single-sheet workbook.
    Sheet.Copy
    ' Reference, save and close the new workbook.
    Dim nwb As Workbook: Set nwb = Workbooks(Workbooks.Count)
    Application.DisplayAlerts = False ' overwrite without confirmation
        nwb.SaveAs Sheet.Parent.Path & Application.PathSeparator & Sheet.Name
    Application.DisplayAlerts = True
    nwb.Close False
End Sub

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

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