0

I'm searching how i can copy the activesheet in vba , i'm wanting to paste it in another workbook ( which is closed ).

Normaly i tried this but it fails :

 Workbooks.Open Filename:=ThisWorkbook.Path & "\target.xlsx" 
ThisWorkbook.ActiveSheet.Copy After:=Workbooks("target.xlsx").Sheets(Workbooks("target.xlsx").Worksheets.Count) 
Tou Mou
  • 1,270
  • 5
  • 16

1 Answers1

4

Workbooks.Open is a function. It returns a Workbook object reference, pointing to the Workbook object that was just opened.

Workbooks.Open Filename:=ThisWorkbook.Path & "\target.xlsx"

You are discarding that reference.

Capture it!

Dim targetBook As Workbook
Set targetBook = Workbooks.Open(ThisWorkbook.Path & "\target.xlsx")

Now instead of dereferencing that workbook from the Workbooks collection everytime you need it...

ThisWorkbook.ActiveSheet.Copy After:=Workbooks("target.xlsx").Sheets(Workbooks("target.xlsx").Worksheets.Count) 

Simply use the object you've got:

ThisWorkbook.ActiveSheet.Copy After:=targetBook.Sheets(targetBook.Worksheets.Count)

And when you're done, invoke it's Close method to close it:

targetBook.Close SaveChanges:=True
Mathieu Guindon
  • 69,817
  • 8
  • 107
  • 235