简体   繁体   中英

Subscript out of range - copy worksheet to new workbook Excel

I'm attempting very simple process, where I am copying one worksheet to a new workbook as shown in the following code:

Private Sub btn_Documents_Click()
    Dim LastRow As Integer
    Dim printrange As Range
    Dim NewWorkbook As Workbook

    Set NewWorkbook = Workbooks.Add
    With NewWorkbook

    .Title = "Document Register"
    .SaveAs Filename:="some file path" & " Program documents status.xlsx"
End With
Workbooks("COFFIE Project Tracker V2.0.0.0").worksheets("Document Register").Copy Before:=NewWorkbook.Sheets("Sheet1")

Unload Me
frm_Control.Show

End Sub

This exact code has worked for me previously, however, this time it is throwing a subscript out of range error on the copy line of the code. I have double checked the file name, name of the sheet I am copying from, and it is all correct, so I am now at a loss as to why its is throwing this error.

Why not simply copy the worksheet directly to a new workbook (without manually creating the target workbook)?

Workbooks("COFFIE Project Tracker V2.0.0.0").worksheets("Document Register").Copy
with activeworkbook
     .Title = "Document Register"
     .SaveAs Filename:="some file path" & " Program documents statusx", FileFormat:=xlOpenXMLWorkbook
end with

Note that I am using the FileFormat parameter of .SaveAs and discarding the file extension from the filename.

If you need to use the NewWorkbook workbook object for something else than what you have shown, it is easy enough to set it to the activeworkbook you created on the copy-to-new-workbook-on-the-fly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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