scb998
scb998

Reputation: 909

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.

Upvotes: 3

Views: 1746

Answers (1)

user4039065
user4039065

Reputation:

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.

Upvotes: 3

Related Questions